假设文本文件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!
答案 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