简介
这可以通过这个sed 脚本来完成:
sed '/BLAH/{s/ \w+$/ newfoo/;h};${x;/BLAH/ba;x;s/$/\nsetenv BLAH newfoo/;x;:a;x}'
说明
sed -e '
/^\(\|.*\W\)BLAH\(\W.*\|\)$/{ # lines matching word BLAH
s/ \w\+$/ newfoo/; # replace last word by "newfoo"
h; # Store for not adding them at end of file
};
${ # On last line...
x; # Swap stored line with current line
/BLAH/ba; # if match, branch to label a:
x; # Swap back
s/$/\nsetenv BLAH newfoo/; # Replace end of line with newline...
x; # Swap again
:a; # Label a:
x # Swap back
}'
您可以使用 in place edition 开关:
sed -e'/BLAH/{h};${x;/BLAH/ba;x;s/$/\nsetenv BLAH newfoo/;x;:a;x}' -i text.txt
为了更准确,搜索分隔词BLAH:
sed -e '
/^\(.*\W\|\)BLAH\(\W.*\|\)$/{h}; # Store lines matching word BLAH
${ # On last line...
x; # Swap stored line with current line
/./ba; # if match, branch to label a:
x; # Swap back
s/$/\nsetenv BLAH newfoo/; # Replace end of line with newline...
x; # Swap again
:a; # Label a:
x # Swap back
}' <(echo BLAH=foo;seq 1 4)
BLAH=foo
1
2
3
4
同时
sed -e '
/^\(.*\W\|\)BLAH\(\W.*\|\)$/{h}; # Store lines matching word BLAH
${ # On last line...
x; # Swap stored line with current line
/./ba; # if match, branch to label a:
x; # Swap back
s/$/\nsetenv BLAH newfoo/; # Replace end of line with newline...
x; # Swap again
:a; # Label a:
x # Swap back
}' <(echo BLAHBLAH=foo;seq 1 4)
BLAHBLAH=foo
1
2
3
4
setenv BLAH newfoo
您可能会看到第二个BLAH 被. 替换。可以这样做,因为如果没有找到 1st,则交换空间是空的。所以如果至少有一个字符,这意味着第一个确实发生了。
清理和脚本
有一种方法可以让这更脚本化:
sedcmd='/^\(.*\W\|\)%s\(\W.*\|\)$/{s/ \w\+$/ %s/;h};'
sedcmd+='${x;/./ba;x;s/$/\\nsetenv %s %s/;x;:a;x}'
varnam=BLAH
varcnt=foo
filnam=/tmp/file.txt
printf -v sedcmd "$sedcmd" ${varnam} ${varcnt} ${varnam} ${varcnt}
sed -e "$sedcmd" -i "$filnam"
您可以删除最后一行的-i 开关...
你可以通过运行来试试这个:
sed -e "$sedcmd" <(echo setenv BLAH oldfoo;seq 1 4)
setenv BLAH foo
1
2
3
4
sed -e "$sedcmd" <(echo setenv BLAHBLAH oldfoo;seq 1 4)
setenv BLAHBLAH oldfoo
1
2
3
4
setenv BLAH foo