在使用sed插入包含4个制表符的字符串时,变量扩展失败。

huangapple go评论46阅读模式
英文:

use variable expansion failing in sed for inserting string with 4 tabs in a file

问题

团队,

我需要在文件的特定行之后的某些制表符后插入一个字符串。

奖励:如果字符串已经存在,则需要跳过插入。

cat test.txt

1
2
3
4
5
sed -i '3i\ \t\t\t\t<file branch-rate="0.0">' test.txt

在上述插入之后查看 test.txt

1
2
                                <file branch-rate="0.0">
3
4
5

使用变量分配

ln=5
sed -i '${ln}i\ \t\t\t\t<file branch-rate="0.0">' test.txt
sed: -e expression #1, char 4: extra characters after command
英文:

Team,

I need to insert a string at a certain line in a file after certain tabs.

bonus: I also need to skip insertion if it already exists.

cat test.txt

1
2
3
4
5
sed -i '3i\ \t\t\t\t<file branch-rate="0.0">' test.txt

cat test.txt < after above insertion.

1
2
                                &lt;file branch-rate=&quot;0.0&quot;&gt;
3
4
5

using variable assignment

ln=5
sed -i &#39;${ln}i\ \t\t\t\t&lt;file branch-rate=&quot;0.0&quot;&gt;&#39; test.txt
sed: -e expression #1, char 4: extra characters after command

答案1

得分: 1

你需要使用双引号 &quot; 以便变量可以展开。同时,在使用原地编辑时,创建备份文件也是一个好主意。

你可以尝试使用以下 sed 命令:

$ sed -i.bak &quot;${ln}i\ \t\t\t\t&lt;file branch-rate=\&quot;0.0\&quot;&gt;&quot; test.txt
英文:

You need to use double quotes &quot; so your variables can expand. It is also a good idea to create a backup file while using in-place editing.

You can try this sed

$ sed -i.bak &quot;${ln}i\ \t\t\t\t&lt;file branch-rate=\&quot;0.0\&quot;&gt;&quot; test.txt

huangapple
  • 本文由 发表于 2023年3月1日 09:46:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定