简体   繁体   English

在 shell 脚本中使用 sed 向文件添加一行

[英]Adding a line to a file using sed in a shell script

I have a file which has 109 lines.我有一个有 109 行的文件。

I perform the two operations on the line shown below.我在下面显示的行上执行两个操作。

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

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

I see line 74 getting deleted from my Test.txt, but for some reasons, now my Test.txt has only 108 lines, and I don't see the This is the string being added to line 109.我看到第 74 行从我的 Test.txt 中删除,但由于某些原因,现在我的 Test.txt 只有 108 行,我没有看到This is the string添加到第 109 行This is the string

I am not sure what the error is.我不确定错误是什么。 How can I fix it?我该如何解决?

You may use this POSIX sed command:你可以使用这个 POSIX sed命令:

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

This will delete 74th line from file and append a line in the end and will save changes inline.这将从文件中删除第 74 行并在最后添加一行并将保存内联更改。

Note that this will work with gnu-sed as well.请注意,这也适用于gnu-sed

If you remove a line, the file has only 108 lines left.如果删除一行,文件只剩下 108 行。 Correct your second command accordingly:相应地更正您的第二个命令:

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

Jonathan already mentioned the potential issues with using sed -i (non-standard, behaves in different ways when supported depending on implementation, etc.).乔纳森已经提到了使用sed -i的潜在问题(非标准,在支持时以不同的方式表现,具体取决于实现等)。 Avoid them by using ed to edit files:通过使用ed编辑文件来避免它们:

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

Note how this appends, and then deletes.请注意这是如何追加,然后删除。 Because ed acts on entire files, not a stream of lines, commands to act on specific lines can be in any order.因为ed作用于整个文件,而不是行流,所以作用于特定行的命令可以按任何顺序进行。

Line number 109 does not exist (you removed one, 109-1=108), you must add it before you can enter text into it.行号 109 不存在(您删除了一个,109-1=108),您必须先添加它,然后才能在其中输入文本。

Solution: sed -i '$ a <text>' Test.txt The new line will be added with the selected text.解决方案: sed -i '$ a <text>' Test.txt新行将与所选文本一起添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM