[英]Can I perform a 'non-global' grep and capture only the first match found for each line of input?
[英]grep: highlight only first match of each line when using --color
當我讓grep
突出顯示這樣的匹配時:
echo hello hello | grep --color "hello"
我突出顯示了該行中的所有匹配項,在上述情況下是所有行:
你好你好
如何僅突出顯示第一次出現:
你好你好
我想我可以使用復雜的正則表達式來做到這一點,但我想知道是否有更簡單的解決方案。
使用sed
可以輕松完成:
sed 's/hello/\x1b[31m&\x1b[0m/' file
這只會在每行中為第一個匹配着色。
同樣,您也可以在awk
中執行此操作:
awk '{sub(/hello/, "\x1b[31m&\x1b[0m")} 1' file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.