Shriram
Shriram

Reputation: 4411

delete and replace a line using linux command

I am trying to delete a line with the pattern matches and replacing the entire line with the another line using sed command. File contents:Sample.txt

Testfile=xxxx
Testfile3=uuuu
Testfile4=oooo
Testfile5=iiii
Testfile2=ikeii

I am using sed command to delete a line contains Testfile3=* and replace by Testfile3=linechanged

sed -i 's/Testfile3=\*/Testfile3=linechanged/' Sample.txt.

But it just appends the replaceable string in the line as shown below

Testfile3=linechanged=uuuu.

I am expecting the output to be

Testfile3=linechanged.

What i am doing wrong?

Upvotes: 2

Views: 4208

Answers (3)

potong
potong

Reputation: 58483

This might work for you (GNU sed):

sed '/Testfile3/cTestfile3=linechanged' file

This matches the line containing Testfile3 and changes it to the required string.

Upvotes: 1

Patrick Trentin
Patrick Trentin

Reputation: 7342

The star is not matched right:

sed -i 's/Testfile3=.*/Testfile3=linechanged/' Sample.txt
#                   ^^

.* matches any character (.) for any length (*), so it will match everything till the end of the line.

Upvotes: 6

heemayl
heemayl

Reputation: 42097

You can use captured group to keep what will be preserved and use the desired replacement for the rest:

sed -i 's/^\(Testfile3=\).*/\1linechanged/' file.txt

In your case, escaping the Regex token * like \* will match * literally e.g. Testfile3=* would be matched then.

Upvotes: 2

Related Questions