Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit sed to certain character range in a line

Tags:

sed

I have a large one line file containing hex codes and I'd like to use sed to find patterns within certain character range of that line.

So far i've tryed this witout succes something like

echo abc123abc123abc123 | sed 's/^\(123\{8,14\}\)/\456/g'

I'd like it to output

abc123abc456abc123   

(replace the pattern 123 only if found between the characters position 8 to 14)

Thanks for your help!

like image 764
Martin Phaneuf Avatar asked Mar 16 '23 05:03

Martin Phaneuf


1 Answers

This replaces the first occurrence of 123 within the character positions 8 to 14 with 456:

$ echo abc123abc123abc123 | sed -r 's/^(.{7,11})123/\1456/'
abc123abc456abc123

With Mac OSX (BSD), try:

sed -E -e 's/^(.{7,11})123/\1456/'

This works by looking for the pattern ^(.{7,11})123 and replacing it with the match in parens, \1 and 456. If 123 starts in the 8th position, that means that it has seven characters that precede it. If it finishes in the 14th position, that means that it has 11 characters which precede it. That is why we match ^(.{7,11}).

Global Replace

If you want to replace all occurrences of 123 with 456 provided that the 123 occurs within positions 8 and 14, then use:

sed -r ':again; s/^(.{7,11})123/\1456/; t again;'

This keeps repeating the substitution until there are no more strings 123 within the character range.

On OSX/BSD, try:

sed -E -e ':again' -e 's/^(.{7,11})123/\1456/' -e 't again'
like image 85
John1024 Avatar answered Apr 25 '23 05:04

John1024