使用命令替换sed脚本里面,带参数
我试图写,我用sed来查找流的简短的脚本,然后基于一个shell功能,这需要从sed的参数结果流进行替换,例如。
I am trying to write a short script in which I use sed to search a stream, then perform a substitution on the stream based on the results of a shell function, which requires arguments from sed, e.g.
#!/bin/sh
function test {
echo "running test"
echo $1
}
sed -n -e "s/.*\(00\).*/$(test)/p" < testfile.txt
在这里TESTFILE.TXT包括:
where testfile.txt contains:
1234
2345
3006
4567
(每间换行;他们越来越贵网站格式化删除)。这样就OK了剧本对我的作品(输出运行测试),但显然没有参数传递给测试。我想用sed行是这样的:
(with newlines between each; they are getting removed by your sites formatting). So ok that script works for me (output "running test"), but obviously has no arguments passed to test. I would like the sed line to be something like:
sed -n -e "s/.*\(00\).*/$(test \1)/p" < testfile.txt
和输出:
running test
00
这样sed中所匹配的模式被送入作为参数进行测试。我真的没有想到上面的工作,但我已经试过的$每个组合()括号,反引号,和逃脱我能想到的,并且可以在任何地方找到没有提及这种情况。帮助?
So that the pattern matched by sed is fed as an argument to test. I didn't really expect the above to work, but I have tried every combination of $() brackets, backticks, and escapes I could think of, and can find no mention of this situation anywhere. Help?
这可能会为你工作:
tester () { echo "running test"; echo $1; }
export -f tester
echo -e "1234\n2345\n3006\n4567" |
sed -n 's/.*\(00\).*/echo "$(tester \1)"/p' | sh
running test
00
或者,如果你使用GNU sed的:
Or if your using GNU sed:
echo -e "1234\n2345\n3006\n4567" |
sed -n 's/.*\(00\).*/echo "$(tester \1)"/ep'
running test
00
N.B。你必须记住,首先导出功能。
N.B. You must remember to export the function first.