[英]replace a line with bash script
I am trying to replace a line of my file. 我正在尝试替换文件的一行。 I used 我用了
line=" abc"
sed -i "3c ${line}" test.txt
It works but the first space doesn't show up. 它可以工作,但是第一个空间没有显示。 I want the line 3 in test.txt to be 我希望test.txt中的第3行是
abc
rather than 而不是
abc
notice there is a space before abc
. 注意abc
前面有一个空格。 thanks for any suggestions! 感谢您的任何建议!
line="\ abc"
sed -i "3c\
$line" test.txt
Escaping the space will keep it from being trimmed. 逃脱空间将使其不被修剪。
The syntax of a sed replacement command is 's/match/replacement/'
. sed替换命令的语法为's/match/replacement/'
。 In order to find abc and replace it, you need to do something like: 为了找到并替换它,您需要执行以下操作:
line=" abc"
sed -i "s/^abc$/$line/" test.txt
The characters ^
and $
are regular expression meta characters for the beginning and the end of the line, respectively. 字符^
和$
分别是该行开头和结尾的正则表达式元字符。 So ^abc$
will only match lines containing exactly that pattern and then replace it with abc
with the space before it. 因此, ^abc$
将仅匹配完全包含该模式的行,然后将其替换为abc
并带有空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.