例如,有一段文字
[task,line:111] first
second
[demo,line:222] first
[test,line:333] first
[task,line:444] first
second
third
[task,line:555] first
我只想要帶有 [task] 的行和下一行,直到出現另一個 [*]。像下面
[task,line:111] first
second
[task,line:444] first
second
third
[task,line:555] first
如何在 shell 腳本中使用 awk 或其他工具來完成它?我只知道我可以使用
awk '/regex/{print $0>"'$output'"}' $file
獲取帶有 [task] 的行并將它們重定向到另一個檔案。請幫助我。
uj5u.com熱心網友回復:
請您嘗試以下方法:
awk '
/^\[/ { # the line starts with "["
if ($1 ~ /^\[task/) f = 1 # set flag for "[task" line
else f = 0 # otherwise reset the flag
}
f {print} # if flag is set, print the line
' input_file > output_file
然后 output_file 將如下所示:
[task,line:111] first
second
[task,line:444] first
second
third
[task,line:555] first
uj5u.com熱心網友回復:
你可以使用這個awk:
awk 'NF == 2 {isTask = ($1 ~ /^\[task/)} isTask' file
[task,line:111] first
second
[task,line:444] first
second
third
[task,line:555] first
uj5u.com熱心網友回復:
我會AWK按照以下方式利用 GNU 來完成這項任務,讓file.txt內容
[task,line:111] first
second
[demo,line:222] first
[test,line:333] first
[task,line:444] first
second
third
[task,line:555] first
然后
awk 'BEGIN{RS="[";ORS=""}/task/{print "[" $0}' file.txt
給出輸出
[task,line:111] first
second
[task,line:444] first
second
third
[task,line:555] first
說明:我通知 GNUAWK行分隔符 ( RS)是空字串,[輸出行分隔符 ( ORS) 是空字串,即行是介于[and之間的東西[,然后對于其中包含taskI的每一行,print因為[ORS 是空字串,所以不會添加多余的換行符(所需的換行符已經在行中)。如果您想了解RS或ORS閱讀8 個強大的 Awk 內置變數 - FS、OFS、RS、ORS、NR、NF、FILENAME、FNR
(在 gawk 4.2.1 中測驗)
uj5u.com熱心網友回復:
你可以試試rq(https://github.com/fuyuncat/rquery/releases)
[ rquery]$ ./rq -v "v1:'':switch(instr(@raw,','),-1,@v1,substr(@raw,0,instr(@raw,',')))" -q "s @raw,@v1 | e @2 like '[task*' trim @1" samples/nextlines.txt -m error
[task,line:111] first
second
[task,line:444] first
second
third
[task,line:555] first
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/525522.html
標籤:正则表达式壳awk
上一篇:如何在CURL上查詢
