我正在尝试编写一个简短的脚本,在其中我使用 sed 搜索流,然后根据 shell 函数的结果对流执行替换,这需要来自 sed 的参数,例如
#!/bin/sh
function test {
echo "running test"
echo $1
}
sed -n -e "s/.*\(00\).*/$(test)/p" < testfile.txt
其中 testfile.txt 包含:
1234
2345
3006
4567
(每个之间有换行符;它们会被您的网站格式删除)。好吧,脚本对我有用(输出“运行测试”),但显然没有参数传递给测试。我希望 sed 行是这样的:
sed -n -e "s/.*\(00\).*/$(test \1)/p" < testfile.txt
和输出:
running test
00
因此 sed 匹配的模式被作为参数提供给 test。我真的没想到上面的方法会起作用,但我已经尝试了我能想到的 $() 括号、反引号和转义符的所有组合,但在任何地方都找不到这种情况的提及。帮忙?
最佳答案
Sed 不会执行命令。但是,Perl 会在正则表达式命令中使用 /e
选项。
perl -pe 'sub testit { print STDERR "running test"; return @_[0]; }; s/.*(00).*/testit($1)/e' <testfile.txt
如果您不想在线看到它并搞砸输出,请将 stderr 重定向到/dev/null。
关于linux - 在 sed 脚本中使用带有参数的命令替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6355443/