Limit a series to a specific range of characters in a string

I have a large file with one line containing hex codes and I would like to use sed to search for patterns in a specific character range of that line.

So far I have tried to make this witout get something like

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

      

I would like it to output

abc123abc456abc123   

      

(replace pattern 123 only if it is between character positions 8-14)

Thank you for your help!

+3


source to share


3 answers


This replaces the first occurrence 123

at character positions 8 through 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 a pattern ^(.{7,11})123

and replacing it with a match in parens, \1

and 456

. If it 123

starts at the 8th position, it means there are seven characters before it. If it ends at the 14th position, it means that it has 11 characters that precede it. This is why we are matching ^(.{7,11})

.

Global replacement



If you want to replace all occurrences of 123 with 456, assuming 123 occurs at positions 8 and 14, use:

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

      

This repeats the substitution until there are no more lines in the character range 123

.

On OSX / BSD try:

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

      

+3


source


All you need to change is the matching pattern:

^.{8}[^0-9]{0,6}([0-9]{3}).*$

      



Here I assumed that you only want to replace numbers 0-9

. If this is not what you wanted, you must provide additional information, an example of the original data, and indicate formally how to match the sequence for replacement.

+1


source


Here's the solution awk

:

echo abc123abc123abc123 | awk '{a=substr($0,1,6);b=substr($0,7,6);c=substr($0,13);sub(/123/,"456",b);print a b c}' file
abc123abc456abc123

      

0


source







All Articles