linux shell sed単引用符、二重引用符、反引用符、斜棒、反斜棒('/)
前言:
この内容を見ると、私と同じようにめまいがして、ルールが見つからないと思います.実はshellが柔軟なためです.
実は次の原則に従って、わけのわからない事故(髪の毛を少なくする)を避けることができます.
1)反引用符(`)を絶対に使わず、$()を断固として使う
2)エスケープを必要としない文字列に対しては,断固として一重引用符で囲む.(反斜棒、二重引用符、または引用符を付けない場合、特殊な変化があります)
例:
/opt/syb/test # echo\opt\tmp\| sed 's:\\:\\\\:g' opttmp
echo "\opt\tmp\"| sed 's:\\:\\\\:g' > ^C
惊いて惊いて意外ではありませんか???!!!
推奨方法:
echo '\opt' | sed 's:\\:\\\\:g'
二重引用符も使用できます.
echo '\opt' | sed "s:\\\\:\\\\\\\\:g"
エスケープリスト:
https://www.cnblogs.com/fnlingnzb-learner/p/6839669.html
https://www.cnblogs.com/f-ck-need-u/p/7499309.html
そこでsedがshellとどのように対話するかについての結論を出すことができます.
まとめ:
一重引用符でも二重引用符でも.
照合置換の場合:エスケープが必要\
置換/一致に対して、使用:変換なしで区切り記号として使用
https://unix.stackexchange.com/questions/379572/escaping-both-forward-slash-and-back-slash-with-sed
You need to escape (with backslash
\
) all substituted slashes /
and all backslashes \
separately, so: $ echo "/tmp/test/folder1/test.txt" | sed 's/\//\\\//g'
\/tmp\/test\/folder1\/test.txt
but that's rather unreadable.
However,
sed
allows to use almost any character as a separator instead of /
, this is especially useful when one wants to substitute slash /
itself, as in your case, so using for example semicolon ;
as separator the command would become simpler: echo "/tmp/test/folder1/test.txt" | sed 's;/;\\/;g'
Other cases:
echo "/tmp/test/folder1/test.txt" | sed "s/\//\\\\\//g"
echo "/tmp/test/folder1/test.txt" | sed s/\\//\\\\\\//g
$ sed 's:/:\\/:g' <<
https://unix.stackexchange.com/questions/398646/why-is-a-single-backslash-shown-when-using-quotes.
the backslash retains its special meaning only when followed by one of the following characters: ‘
$
’, ‘ `
’, ‘ "
’, ‘ \
’, or newline
. Within double quotes, backslashes that are followed by one of these characters are removed. 5
Backslash is interpreted differently according context:
The backslash retains its special meaning only when followed
by one of the following characters: $, `, ", \, or .
A non-quoted backslash (\) is the escape character. It
preserves the literal value of the next character that
follows, with the exception of . If a \
pair appears, and the backslash is not itself quoted, the
\ is treated as a line continuation (that is, it is
removed from the input stream and effectively ignored).
$'....'
, where you can use inside the quote the standard backspace character, nearly as in C. e.g.
, \t
, etc. When the old-style backquote form of substitution is used,
backslash retains its literal meaning except when followed by
$, `, or \.