介绍
这可以通过 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
}'
您可以使用 即时编辑 开关:
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
被替换成了
.
。这是因为如果第一个没有被找到,交换空间就是空的。所以如果至少有一个字符,这意味着第一个确实出现了。
清洁和脚本化
有一种方法可以使此过程更加易于脚本化:
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
$
:s/$/\nBLAH=newfoo\nnewfoo=$1\ndir=\o57tmp\o57/;
- F. Hauri - Give Up GitHubsed -e "/^\(.*\W\|\)BLAH\(\W.*\|\)$/{h};${x;/./ba;x;s/$/\nexport BLAH=FOO\nFOO=$1/;x;:a;x}" -i $FILE
- Jaison Brooks"
)而不是单引号('
),则还必须转义$
符号和反斜杠。:sed -e "/^\\(.*\\W\\|\\)BLAH\\(\\W.*\\|\\)\$/{h};\${x;/./ba;x;s/$/\\nsetenv BLAH newfoo=\$1/;x;:a;x}" <(echo BLAH=foo;seq 1 4)
- F. Hauri - Give Up GitHub