我正在嘗試使用以下命令從 MacOS 使用 sed 洗掉字串中的重復單詞:
sed -r 's/^([A-Za-z0-9_] ) \1$/\1/' <<< 'The best of of The United Kingdom'
但它只會回傳
The best of of United Kingdom
我缺少什么?你們可以把手給我嗎?請。
uj5u.com熱心網友回復:
你可以試試這個 sed
$ sed 's/\([^ ]* \)\1\ /\1/' input_file
The best of The United Kingdom
您的原始代碼有不需要的錨點^|$。這是一個固定版本
$ sed -r 's/([A-Za-z0-9_]* )\1 /\1/' <<< 'The best of of The United Kingdom'
The best of The United Kingdom
uj5u.com熱心網友回復:
我安裝了 gnu-sed。問題解決了。
uj5u.com熱心網友回復:
您不必要地在行首和行尾錨定正則運算式。洗掉^和$。更改-r為 POSIX -E,它將在 BSD/Mac sed 上運行。您還需要該g標志來替換多個重復的單詞模式。
sed -E 's/([A-Za-z0-9_] ) \1/\1/g'
uj5u.com熱心網友回復:
利用
sed -E 's/[[:<:]]([[:alnum:]_] )([[:space:]] \1) [[:>:]]/\1/'
解釋
--------------------------------------------------------------------------------
[[:<:]] the boundary between a non-word char or
start of string and a word char
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[[:alnum:]_] any character of: letters and digits,
'_' (1 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
( group and capture to \2 (1 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[[:space:]] any character of: whitespace characters
(like \s) (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
\1 what was matched by capture \1
--------------------------------------------------------------------------------
) end of \2
--------------------------------------------------------------------------------
[[:>:]] the boundary between a word char (\w) and
something that is not a word char
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401784.html
上一篇:VisualStudio2022winform設計器在任何控制元件的屬性視窗中不顯示ApplicationSettings
