簡體   English   中英

如何在 grep 中為每個匹配的輸出添加一些文本前綴?

[英]How can I prefix the output of each match in grep with some text?

我有一個包含短語列表的文件

apples
banananas
oranges

我正在運行cat file.txt | xargs -I% sh -c "grep -Eio '(an)' >> output.txt" cat file.txt | xargs -I% sh -c "grep -Eio '(an)' >> output.txt"

我無法弄清楚的是,我希望輸出包含原始行,例如:

bananas,an
oranges,an

如何為 grep 的輸出添加前綴以包含通過管道傳輸到它的值?

這應該是awk的任務,請您嘗試以下操作。

awk '/an/{print $0",an"}'  Input_file

這將在 Input_file 的所有行中查找字符串an並在其中附加an

sed解決方案:

sed '/an/s/$/,an/' intput_file

這將查找與模式/an/匹配的行,並將,an附加到模式空間$的末尾。

使用 awk 而不是grep

$ awk -v s="an" '                          # search string
BEGIN {
    OFS=","                                # separating comma
}
match($0,s) {                              # when there is a match
    print $0,substr($0,RSTART,RLENGTH)     # output
}' file

輸出:

banananas,an
oranges,an

暫無
暫無

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

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