简体   繁体   中英

Adding a line to a file using sed in a shell script

I have a file which has 109 lines.

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.

I am not sure what the error is. How can I fix it?

You may use this POSIX sed command:

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.

Note that this will work with gnu-sed as well.

If you remove a line, the file has only 108 lines left. 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.). Avoid them by using ed to edit files:

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.

Line number 109 does not exist (you removed one, 109-1=108), you must add it before you can enter text into it.

Solution: sed -i '$ a <text>' Test.txt The new line will be added with the selected text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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