Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace particular string at fixed position using sed

Tags:

sed

I have a simple text file containing several lines of data where each line has got exactly 26 characters. E.g.

10001340100491938001945591
10001340100491951002049591
10001340100462055002108507
10001340100492124002135591
10001340100492145002156507
10001340100472204002205591

Now, I want to replace 12th and 13th character if only these two characters are 49 with characters 58.

I tried it like this:

sed 's/^(.{12})49/\58/' data.txt

but am getting this error:

sed: -e expression #1, char 18: invalid reference \5 on `s' command's RHS

Thanks in advance

like image 577
user333422 Avatar asked Dec 12 '22 05:12

user333422


1 Answers

The captured group is \1, so you want to put the 11 (not 12) characters, then 58:

sed -E 's/^(.{11})49/\158/' data.txt

You also need -E or -r if you don't want to escape square and curly brackets.

With your input, the command changes 49 to 58 in lines 1, 2, 4 and 5.

like image 91
Lev Levitsky Avatar answered Apr 12 '23 12:04

Lev Levitsky