![](/img/trans.png)
[英]How to use sed to search and replace a pattern who appears multiple times in the same line?
[英]sed to replace multiple pairs of identical pattern on same line
我要替換包含以下內容的文件test.txt
some text $\alpha$ some text $\alpha$ some text
some text $\beta$ some text
some text $\gamma$.
some text $\delta$
$\epsilon$ some text $\epsilon$
$\mu$
some text `$a$` some text `$a$` some text
some text `$b$` some text
some text `$c$`.
some text `$d$`
`$e$` some text `$e$`
`$f$`
$$\Alpha$$
$$\Beta$$
`$$A$$`
`$$B$$`
通過
some text '$\alpha$' some text `$\alpha$` some text
some text '$\beta$' some text
some text '$\gamma$'.
some text '$\delta$'
`$\epsilon$` some text `$\epsilon$`
`$\mu$`
some text `$a$` some text
some text `$b$` some text
some text `$c$`.
some text `$d$`
`$e$` some text `$e$`
`$m$`
`$$\Alpha$$`
`$$\Beta$$`
`$$A$$`
`$$B$$`
簡而言之,我想做替換
$..$ --> `$..$`
和
$$..$$ --> `$$..$$`
在一組sed
命令中。 但是,如果將命令集重新應用到文件上,則不應添加額外的(`)符號。
到目前為止,我已經嘗試了以下設置:
sed -e 's/^\(\$\$.*\$\$\)/`\1`/g' -i test.txt
sed -e 's/[^`]\(\$\$[^`].*[^\$]\$\$\)[^`]/`\1`/g' -i test.txt
sed -e 's/^\(\$.[^\$]*\$\)/`\1`/g' -i test.txt
sed -e 's/[^`$$]\(\$[^`].[^\$]*\$\)[^`$$]/ `\1` /g' -i test.txt
但這不能完全起作用...
您應該可以使用一個sed
表達式下車:
# ERE
sed -E 's/([^`$]|^)(\${1,2}[^`$]+\${1,2})([^`$]|$)/\1`\2`\3/g' test.txt
# or, if you prefer BRE (but only with GNU sed)
sed 's/\([^`$]\|^\)\(\$\{1,2\}[^`$]\+\$\{1,2\}\)\([^`$]\|$\)/\1`\2`\3/g' test.txt
給你:
some text `$\alpha$` some text `$\alpha$` some text
some text `$\beta$` some text
some text `$\gamma$`.
some text `$\delta$`
`$\epsilon$` some text `$\epsilon$`
`$\mu$`
some text `$a$` some text `$a$` some text
some text `$b$` some text
some text `$c$`.
some text `$d$`
`$e$` some text `$e$`
`$f$`
`$$\Alpha$$`
`$$\Beta$$`
`$$A$$`
`$$B$$`
我們匹配三組:
$
,其次是內容,然后是一/兩$
然后將其打印出來,並在中間的組中加上反引號。 我們需要錨定這些前綴和后綴,以避免您遇到雙引號。
請注意 ,上面的POSIX BRE(基本正則表達式)形式使用了幾個GNU擴展,即:錨定在表達式中間使用的行首和行尾(而不是模式中的第一個/最后一個字符),交替( \\|
)和一個或多個復制運算符( \\+
)。 如果需要此表達式在POSIX BRE中運行,則需要將其分成幾個(即3個)子表達式,並使用\\{1,\\}
而不是\\+
。
但也請注意,給定的POSIX ERE(擴展正則表達式)格式應在GNU和BSD系統上的所有現代sed
環境中均適用。
如果您有perl
則使用環視正則表達式(sed regex不支持)會更加容易:
perl -pe 's/(?<!`)(\$++[^\s\$]*\$++)(?!`)/`$1`/g' file
some text `$\alpha$` some text `$\alpha$` some text
some text `$\beta$` some text
some text `$\gamma$`.
some text `$\delta$`
`$\epsilon$` some text
`$\mu$`
some text `$a$` some text `$a$` some text
some text `$b$` some text
some text `$c$`.
some text `$d$`
`$e$` some text
`$f$`
`$$\Alpha$$`
`$$\Beta$$`
`$$A$$`
`$$B$$`
要將更改保存回文件,請使用:
perl -i -pe 's/(?<!`)(\$++[^\s\$]*\$++)(?!`)/`$1`/g' file
正則表達式分解:
(?<!`) - Negative Lookbehind to assert previous character is not `
( - Star captured group #1
\$++ - Match one or more $
[^\s\$]* - Match zero or more non-whitespace non-$ characters
\$++ - Match one or more $
) - End captured group #1
(?!`) - Negative Lookahead to assert next character is not `
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.