Anna
Anna

Reputation: 181

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?

Upvotes: 1

Views: 3570

Answers (4)

Shawn
Shawn

Reputation: 52439

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.

Upvotes: 1

Donka
Donka

Reputation: 48

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.

Upvotes: 0

anubhava
anubhava

Reputation: 785276

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.

Upvotes: 2

Cyrus
Cyrus

Reputation: 88654

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

Upvotes: 1

Related Questions