Linux:在文件中查找指定內容並輸出到文件


引用:Linux:在文件中查找指定內容並輸出到文件

一、 關鍵字查詢

  1.查找搜索目標所在行數

$cat xxx.log | grep -n  "查詢關鍵字"

  2.查看搜索目標后2行數據 

$cat xxx.log | grep -A 2  "查詢關鍵字"

  3.查看搜索目標前2行數據 

$cat xxx.log | grep -B 2  "查詢關鍵字"

  4.同時查看搜索目前 前2行和 后2行數據  

$cat xxx.log | grep -C 2  "查詢關鍵字"

  5.查看文件指定行數區間內容 

$sed -n '查詢關鍵字' xxx.log 

二、輸出文件:

1 滿足一個條件

例如:將文件 file1 中包含 name 的行輸出到 file2.

grep 'name' file1 > file2# 
或者cat file1 | grep 'name' > file2

輸入grep后提示 匹配到二進制文件 (標准輸入) 無顯示結果
使用grep -a 'name' file1 > file2# 

2 滿足兩個條件任意一個
 
egrep 'name|age' file1 > file2# 

或者grep -E 'name|age' file1 > file2# 

或者cat file1 | grep -E 'name|age' > file2

 

  

例如:將文件 file1 中包含 name 或者 age 的行輸出到 file2.

 
3 同時滿足兩個條件

例如:將文件 file1 中包含 name 和 age 的行輸出到 file2.

grep 'name' file1 | grep 'age' > file2# 
或者cat file1 | grep 'name' | grep 'age' > file2

  

注意:符號“>”表示擦除文件原內容並寫入;“>>”表示追加內容。

4 命令 grep 和 tee 搭配使用

grep 'name' file1 | tee -a file2


免責聲明!

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



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