简体   繁体   中英

Search and replace with sed in specific intervall after keyword

Assume a textfile file that contains some lines with keyword foo .

> cat file
bar bar baz qux
bar foo bar baz
bar foo qux bar

I would like to replace any occurrence of character r that occurs between (and including) n and m characters after the end of the keyword with the character z .

Example with n=1 and m=3 :

> sought_command file
bar bar baz qux
bar foo baz baz  # Replacement only here!
bar foo qux bar

Example with n=4 and m=6 :

> sought_command file
bar bar baz qux
bar foo bar baz
bar foo qux baz  # Replacement only here!

With sed:

n=1;m=3
sed -E ':a;s/(foo( *[^ ]){'"$n"','"$m"'} *)r/\1z/;ta' file

Where :a defines a label and ta jumps to this label until there's no more "r" to replace.

You can use this awk script:

$> cat mark.awk

p = index($0, kw) {           # only for lines containing keyword
   b = p+length(kw) + 1       # get to next position after kw match
   part = substr($0, b+n, m)  # get substring between start and end points
   gsub(/r/, "z", part)       # replace "r" by "z" only in the substring

   # new reconstruct the original line using substr commands
   $0 = substr($0, 1, b+n-1) part (b+m+1<length($0)?substr($0, b+m+1):"")
} 1                           #default action to print a line

Now run this script with your parameters on command line:

$> awk -v kw='foo' -v n=1 -v m=3 -f mark.awk file

bar bar baz qux
bar foo baz baz
bar foo qux bar

$> awk -v kw='foo' -v n=4 -v m=6 -f mark.awk file

bar bar baz qux
bar foo bar baz
bar foo qux baz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM