簡體   English   中英

Unix - 在 grep 結果行之間添加字符串

[英]Unix - Add string between grep resulted lines

任何人都知道一種方法(在 RHEL7 和 AIX5 上工作)來制作在 /bin/bash 或 /bin/ksh 上運行的腳本,以使用 grep(或其他函數)在文本文件中搜索 1 個或多個字符串,結果被放入一個變量中,但在該變量中在每次出現的末尾放置一個字符串“\\\\n”?

例如:

文本文件1.txt

[root@server ~]$ cat TextFile1.txt
aby ORA-3120: unable to xx
sxyy  unable to aa
sxyy ORA-3120: unable to aa
ytxy  unable to bb
y41y  unable to dd
yanby  unable to ff
ytxy ORA-3120: unable to bb
y41y ORA-3120: unable to dd
y124gby  unable to gg
yanby ORA-3120: unable to ff
aby  unable to xx
y124gby ORA-3120: unable to gg

簡單的 Grep

[root@server ~]$ cat TextFile1.txt | grep "ORA-"
aby ORA-3120: unable to xx
sxyy ORA-3120: unable to aa
ytxy ORA-3120: unable to bb
y41y ORA-3120: unable to dd
yanby ORA-3120: unable to ff
y124gby ORA-3120: unable to gg

將結果放入變量中

[root@server ~]$ aa=$(cat TextFile1.txt | grep "ORA-")

[root@server ~]$ echo $aa
aby ORA-3120: unable to xx sxyy ORA-3120: unable to aa ytxy ORA-3120: unable to bb y41y ORA-3120: unable to dd yanby ORA-3120: unable to ff y124gby ORA-3120: unable to gg

想要的結果:

[root@server ~]$ echo $aa

\\\\n aby ORA-3120:無法 xx \\\\n sxyy ORA-3120:無法 aa \\\\n ytxy ORA-3120:無法 bb \\\\n y41y ORA-3120:無法 dd \\\\n yanby ORA- 3120: 無法 ff \\\\n y124gby ORA-3120: 無法 gg \\\\n

預先感謝您的幫助和提示

一種快速解決方案是使用 awk:

aa=$(cat TextFile1.txt | grep "ORA-"| awk '{print $0 "\\n"}')

有很多方法可以做到這一點。 這里有兩個:

管道grep的輸出到sed

aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | sed 's/\(.*\)/\1 \\\\n/')

輸出:

$ aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | sed 's/\(.*\)/\1 \\\\n/')
$ echo $aa
\\n aby ORA-3120: unable to xx \\n sxyy ORA-3120: unable to aa \\n ytxy ORA-3120: unable to bb \\n y41y ORA-3120: unable to dd \\n yanby ORA-3120: unable to ff \\n y124gby ORA-3120: unable to gg \\n
$

管道grep的輸出到 awk:

aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | awk '{print $0 " \\\\n"}')

輸出:

$ aa=$(echo " \\\n"; grep "ORA-" TextFile1.txt | awk '{print $0 " \\\\n"}')
$ echo $aa
\\n aby ORA-3120: unable to xx \\n sxyy ORA-3120: unable to aa \\n ytxy ORA-3120: unable to bb \\n y41y ORA-3120: unable to dd \\n yanby ORA-3120: unable to ff \\n y124gby ORA-3120: unable to gg \\n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM