我想用空格字符串替换包含不同长度波浪字符的字符串。例如,如果一个字符串包含 5 个波浪号字符: ~~~~~
,那么我想用 5 个空格替换它。
我当前的sed
命令:
sed -e '/\\begin{alltt}/,/\\end{alltt}/s/~\+/ /' test.tex
我可以检查一个或多个波浪号字符,但不知道如何检索长度以插入空格
sed '/\\begin{alltt}/,/\\end{alltt}/s/~/ /g'
Run Code Online (Sandbox Code Playgroud)
将~
用空格替换所有的s。如果您只想替换每一行~
上第一个~
s序列中的s,您可以执行以下操作:
sed '
/\\begin{alltt}/,/\\end{alltt}/{
/~/ {
h; # save a copy
s/\(~\{1,\}\).*/\1/; # remove everything after the first sequence of ~s
s/~/ /g; # replace ~s with spaces
G; # append the saved copy
s/\n[^~]*~*//; # retain only what's past the first sequence of ~s
# from the copy
}
}'
Run Code Online (Sandbox Code Playgroud)
注意:\{1,\}
是\+
GNU 扩展的标准等价物。
使用perl
以下方法更容易:
perl -pe 's{~+}{$& =~ s/~/ /gr}e if /\\begin\{alltt\}/ .. /\\end\{alttt\}/'
Run Code Online (Sandbox Code Playgroud)
或者:
perl -pe 's{~+}{" " x length$&}e if /\\begin\{alltt\}/ .. /\\end\{alttt\}/'
Run Code Online (Sandbox Code Playgroud)