[英]Replacing a word containing backslash(\) with sed
I want to replace some strings with other strings in a folder containing .ly files (.ly files are files used to write music, which can then be converted to svg files). 我想用包含.ly文件的文件夹中的其他字符串替换一些字符串(.ly文件是用于写入音乐的文件,然后可以将其转换为svg文件)。 One problem is that the files contain backslashes (\\). 一个问题是文件包含反斜杠(\\)。
Anyway, what I want to do is to replace the following strings: 无论如何,我要替换以下字符串:
\f with \fffff
\p with \ppppp
mordent with reverseturn
r4 with \mordent
Each string I want to replace (and each string it is replaced for) has a space in the end. 我要替换的每个字符串(及其替换的每个字符串)的末尾都有一个空格。 This is because I don't want strings like 这是因为我不要像这样的字符串
\pt to be replaced with \pppppt
Similarly, because backslashes matter, strings like 同样,因为反斜杠很重要,所以像
\ff should stay the same (only f with a slash before and a space after should be replaced).
The code that I am using to achieve this is: 我用来实现此目的的代码是:
for f in *.ly
do
filename="${f}"
sed -i -- "s@\p @\ppppp @g; s@\f @\fffff @g; s@mordent @reverseturn @g; s@r4 @\maxima @g" $filename;
done
I am using delimited @ instead of backslash exactly to achieve this. 我正在使用定界@而不是反斜杠来实现此目的。
However, the program is giving some totally weird behavior. 但是,该程序给出了一些完全奇怪的行为。 In particular: 尤其是:
\f stays the same (wrong behavior, the right behavior is to get transformed to \fffff)
\p is converted to \ppppp (correct behavior)
\stemUp is converted to \stemUppppp (wrong behavior, the right behavior is to remain as it was)
This is perplexing me and giving me a headache. 这让我感到困惑,使我头疼。 In particular, why it works correctly for \\p but not for \\f considering that it is the exact same code. 特别是,考虑到它是完全相同的代码,为什么它对于\\ p正确运行,但对于\\ f却不正确。
For reference, I attached a file before and after applying the sed commands. 作为参考,我在应用sed命令之前和之后附加了一个文件。
Thanks in advance for any help! 在此先感谢您的帮助!
NB: I am using Ubuntu 16.04 and sed (GNU 4.2.2). 注意:我正在使用Ubuntu 16.04和sed(GNU 4.2.2)。
$ echo '12p3 p \p foo' | sed 's/\p /\ppppp /g'
12p3 ppppp \ppppp foo
$ echo '12p3 p \p foo' | sed 's/\\p /\\ppppp /g'
12p3 p \ppppp foo
\\
is a meta-character, to match it literally, it needs to be escaped, ie \\\\
\\
是一个元字符,要从字面上进行匹配,需要将其转义,即\\\\
\\
is special within double quotes too(because of bash, nothing to do with sed) - so don't use double quotes unless needed(for ex: sed substitution with bash variables ). \\
在双引号中也很特殊(因为bash与sed无关)-因此,除非需要,否则不要使用双引号(例如: 用bash变量替换sed )。 See also Difference between single and double quotes in Bash 另请参阅Bash中单引号和双引号之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.