在关键字后的特定intervall中搜索和替换sed

时间:2016-10-07 14:20:21

标签: regex awk replace sed pattern-matching

假设文本文件file包含一些带有关键字foo的行。

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

我想替换在关键字结束后出现(包括) n m 字符之间出现的任何字符r字符z

示例 n = 1 m = 3

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

示例 n = 4 m = 6

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

2 个答案:

答案 0 :(得分:1)

使用sed:

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

:a定义了一个标签,ta跳转到此标签,直到不再有" r"替换。

答案 1 :(得分:0)

您可以使用此awk脚本:

$> 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

现在在命令行上使用您的参数运行此脚本:

$> 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