[英]Extract a particular string from a file and output to another file using grep, awk, sed
[英]Output to specific areas of a file to another file using awk or sed?
我有一個看起來像這樣的文件:
d "Text 1":6,64;1 /filesys1/db1.d2
d "Text 2":6,64;1 /filesys1/db1.d2 f 730
d "Text 3":6,64;1 /filesys1/db1.d2
d "TextA":6,64;1 /filesys1/db1.d2 f 46000
d "TextB":6,64;1 /filesys1/db1.d2
d "TextC":6,64;1 /filesys1/db1.d2 f 120000
...
我需要從引號之間獲取所有內容,然后獲取該行的最后2個字符並將其放入新文件中。 我可以單獨做兩件,但我不能將它們組合起來並讓它起作用。
awk -F'"' '$0=$2' datatmp4 > dataout2
會得到我:
Text 1
Text 2
Text 3
TextA
TextB
TextC
和
awk '{ print substr( $NF, length($NF) -1, length($NF) ) }' datatmp4 > dataout
會得到我:
d2
30
d2
00
d2
00
我需要的是:
Text 1 d2
Text 2 30
Text 3 d2
TextA 00
TextB d2
TextC 00
您可以使用$ 2連接引號之間的文本以及最后2個字符的結果,如下所示:
awk -F '"' '{print $2, substr($NF, length($NF)-1, length($NF))}' datatmp4 > dataout
你在自己身上做得太難了。 當你想要的只是整行的最后2個字符時,沒有理由關心或嘗試操作線上的最后一個字段($ NF):
$ awk -F'"' '{print $2, substr($0,length()-1)}' file
Text 1 d2
Text 2 30
Text 3 2
TextA 00
TextB d2
TextC 00
輸出的第三行以2<blank>
結尾,因為這是輸入文件中的內容。 這與你發布的所需輸出不符,但是要清楚 - 你是否想要我顯示的每行的最后一個字符,你說你想要的,或者你想要你發布的暗示的最后2個非空白字符嗎?期望的輸出?
$ awk -F"\"" '{match($NF,/..$/,a); print $2,a[0]}' last2
Text 1 d2
Text 2 30
Text 3 2
TextA 00
TextB d2
TextC 00
使用sed(BRE):
sed 's/^[^"]*"\([^"]*\).*\(.[^ ]\)/\1 \2/;' file
sed(ERE)的另一種方式:
sed -E 's/^[^"]*"|"[^ ]*( ).*(.[^ ])/\1\2/g' file
用awk:
awk -F'"' '{ print $2 " " gensub(/.*(.[^ ])/, "\\1", 1)}' file
字段分隔符是引用。 gensub
替換除了最后2個字符之外的所有字符(第二個字符不能是空格)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.