在shell脚本中使用sed将行添加到文件中

问题描述 投票:1回答:4

我有一个包含109行的文件。

我在下面显示的行上执行两项操作。

# Delete line 74
sed -i '74d' Test.txt

# Add the entry to line 109
  sed -i "109iThis is the string" Test.txt

[我看到第74行从我的Test.txt中删除,但是由于某些原因,现在我的Test.txt只有108行,我看不到This is the string被添加到第109行。

我不确定是什么错误。我该如何解决?

bash shell sed ksh
4个回答
1
投票

[Jonathan已经提到了使用sed -i的潜在问题(非标准,根据实现等受支持时,行为方式不同)。通过使用ed编辑文件来避免它们:

ed -s Test.txt <<EOF
109a
This is the string
.
74d
w
EOF

请注意这是如何追加,然后删除。因为ed作用于整个文件而不是行流,所以作用于特定行的命令可以是任意顺序。


2
投票

您可以使用此POSIX sed命令:

sed -i.bak '74d; $ a\
This is the string
' file

这将从文件中删除第74行,并在末尾添加一行,并保存内联的更改。

注意,这也适用于gnu-sed


1
投票

如果删除一行,则文件仅剩108行。相应地更正您的第二个命令:

sed -i "108iThis is the string" Test.txt

0
投票

行号109不存在(您删除了行号109-1 = 108),必须先添加行号,然后才能在其中输入文本。

解决方案:sed -i '$ a <text>' Test.txt新行将添加所选文本。

© www.soinside.com 2019 - 2024. All rights reserved.