[英]Execute command on the same line multiple times with sed
我需要用*
符號突出顯示文本中的每個重復單詞。
例如
lol foo lol bar foo bar
應該
lol foo *lol* bar *foo* *bar*
我嘗試使用以下命令:
echo "lol foo lol bar foo bar" | sed -r -e 's/(\b[a-zA-Z]+\b)([^*]+)(\1)/\1\2*\3*/'
它給了我:
lol foo *lol* bar foo bar
然后我添加了g
標志:
lol foo *lol* bar foo *bar*
但foo
沒有突出顯示。
我知道發生這種情況是因為如果發現匹配, sed
不會 sed
。
我可以只sed
處理嗎?
Sed
不是完成此任務的最佳工具。 它沒有前瞻,后瞻和非貪婪量詞,但嘗試使用以下命令:
sed -r -e ':a ; s/\b([a-zA-Z]+)\b(.*) (\1)( |$)/\1\2 *\3* / ; ta'
它使用條件分支來執行替換命令,直到失敗。 此外,你不能檢查([^*]+)
因為第二輪它必須遍歷第一個替換的一些*
,你的選擇是貪婪.*
。 最后,你不能匹配(\\1)
只因為它會一次又一次匹配第一個字符串lol
。 你需要一些像空格或行尾包圍的上下文。
該命令產生:
lol foo *lol* bar *foo* *bar*
更新 : potong在評論中提供的改進:
sed -r ':a;s/\b(([[:alpha:]]+)\s.*\s)\2\b/\1*\2*/;ta' file
使用awk
awk '{for (i=1;i<=NF;i++) if (a[$i]++>=1) printf "*%s* ",$i; else printf "%s ",$i; print ""}' file
lol foo *lol* bar *foo* *bar*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.