Linux命令-grep,sed,awk


grep


(global search regular expression[RE] and print out the line)
正則表達式全局搜索並將行打印出來

  • 在文件中查找包含字符串"text"的行
grep text local_file
grep "text" local_file #另一種方式
grep "text" local_file1 local_file2 ...  #查找多個文件
  • 在文件中查找包含字符串"text"的行
grep -v "text" local_file
  • 忽略大小寫
grep -i "TeXt" local_file
grep -y "TeXt" local_file
  • 不顯示錯誤信息,常用於腳本文件中
grep -s "text" local_file
  • 只打印出匹配到的字符串
grep -o "text" local_file
  • 統計文件中有多少行包含需要查找的字符串
grep -c "text" local_file
  • 不輸出信息,命令運行成功返回0.失敗返回非0值,用於判斷
grep -q "text" local_file
  • 匹配多個字符串,相當於邏輯中的或
grep -e "text1" -e "text2" local_file
  • 遞歸查找,用於多級目錄中的文件
grep -r "text" . #在當前目錄下進行查找
  • 輸出匹配需要查找字符串的行以及之前的行
grep "text" -B 3 local_file #輸出之前的3行
  • 輸出匹配需要查找字符串的行以及之后的行
grep "text" -A 3 local_file #輸出之后的3行

sed


流編輯器,用來編輯一個或者多個文件,簡化對文件的重復操作。在緩沖區內操作,除非特別指定,不對文件本身內容進行修改。

-i

對文件本身進行修改

-q

  • 打印出第2行后退出sed
sed '2q' local_file

查找

  • 查找第2-5行數據
sed '2,5p' local_file
sed -n '2,5p' local_file #並打印行號
  • 查找包含字符串"text"的行與包含字符串"file"的行范圍內的行
sed '/text/,/file/p' local_file
  • 查找從第2行開始一直到以字符串"text“開頭的行之間的所有行
sed '2,/^text/p' local_file

添加

  • 在第2行后面一行添加字符串"text"
sed '2a text' local_file
  • 在第二行前面一行添加字符串"text"
sed '2i text' local_file
  • 在每一個單詞前面加上字符"a":
sed 's/\w\+/a&/g'  # \w\+匹配每一個單詞 &對應之前匹配的每一個單詞

替換

  • 替換字符串filefiles
sed 's/file/files/g' local_file #打印到控制台,不修改文件
sed 's:file:file:g' local_file # /標記可以使用其他符號代替
sed -i 's/file/files/g' local_file #修改文件本身內容,不打印到控制台
  • 替換第2-5行為字符串"text"
sed '2,5c text' local_file

刪除

  • 刪除文件內的第2-5行
sed '/2,5/d' local_file
  • 刪除開頭字符串為"text"的行
sed '/^text.*//g' local_file
sed '/^text/'d local_file
  • 刪除最后一行
sed '$d' local_file
  • 刪除空白行
sed '/^$/d' local_file

awk


  • 打印每一行的第2,3列數據
awk '{print $2,$3}' local_file


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM