MacOS sed:匹配開頭或結尾

MacOS sed:匹配開頭或結尾

這已經困擾我好幾年了。

「匹配這個或那個」有效。
「匹配行首」有效。
「匹配行尾」有效。
“匹配行首或行尾”,沒有那麼多。

全部在 MacOS 上。

echo "hello world" | sed -E 's/(h|d)/X/g'
Xello worlX

echo "hello world" | sed -E 's/(^)/X/g'
Xhello world

echo "hello world" | sed -E 's/($)/X/g'
hello worldX

echo "hello world" | sed -E 's/(^|$)/X/g'
Xhello world

答案1

這可能是 MacOSsed實作中的錯誤。

你的語法在 FreeBSD 12 和 Ubuntu 18 下適用於我:

$ sed -E 's/(^|$)/X/g'
Xhello worldX

也許這個解決方法足以滿足您的需求,直到錯誤解決:

$ echo "hello world" | sed -E -e 's/^/X/' -e 's/$/X/'
Xhello worldX

鑑於您對複雜替換字串的評論,上面的內容可以更概括一些,但代價是稍微複雜一些:

$ X='replacement text here'
$ printf "echo 'hello world' | sed -E -e 's/^/%s/' -e 's/$/%s/'" "$X" "$X" | sh 
replacement text herehello worldreplacement text here

相關內容