Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete and replace a line using linux command

Tags:

linux

bash

sed

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?

like image 270
Shriram Avatar asked Aug 03 '26 10:08

Shriram


2 Answers

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.

like image 129
Patrick Trentin Avatar answered Aug 06 '26 02:08

Patrick Trentin


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.

like image 25
heemayl Avatar answered Aug 06 '26 03:08

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!