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!
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})
.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With