Using dollar sign in sed for both variable replacement and character

前提是你 提交于 2019-12-31 03:50:09

问题


I try to use sed to change a line in a file named convergence.gnu I have a variable named lafila, which is a file name

Currently, I can do:

lafila="nGas060.dat"
sed -i "6s/.*/plot \"$lafila\" using 1:2 with l/" convergence.gnu

This changes correctly the sixth line of my convergence.gnu file to:

plot "nGas062.dat" using 1:2 with l

However, now I want to include a dollar sign in the replaced line to obtain instead:

plot "nGas062.dat" using ($1/1000):2 with l

Can you tell me what to change in my sed command? If I escape a dollar sign it does not work properly. Double dollars also don't work.


回答1:


Use single quotes:

sed -i '6s/.*/plot "'$lafila'" using ($1\/1000):2 with l/' convergence.gnu

Single quotes protect double quotes and $ is not interpreted inside them. However, you do need to escape /.

See also:

  • Difference between single and double quotes in Bash



回答2:


I believe your issue is actually being caused by the forward slash in ($1/1000), which clashes with the slashes being used to delimit the various components of the sed command. You either need to escape that forward slash as well, or alternatively use a different character for delimiting the sed strings. Either of the below should work:

lafila="nGas060.dat"
sed -i "6s/.*/plot \"$lafila\" using (\$1\/1000):2 with l/" convergence.gnu

or

lafila="nGas060.dat"
sed -i "6s,.*,plot \"$lafila\" using (\$1/1000):2 with l," convergence.gnu

Using a different delimiting character can be a good way to make your sed string look neater and avoid the leaning toothpick syndrome.

echo foo | sed "s,foo,/there/are/a/lot/of/slashes/here,"

is much nicer than

echo foo | sed "s/foo/\/there\/are\/a\/lot\/of\/slashes\/here/"



回答3:


Try it:

lafila="nGas060.dat"
sed -i "6s@.*@plot \"$lafila\" using (\\\$1/1000):2 with l@" convergence.gnu

You need only to escape backslash and after the dollar sign.

\\ + \$ == \\\$


来源:https://stackoverflow.com/questions/46842495/using-dollar-sign-in-sed-for-both-variable-replacement-and-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!