使用命令替换sed脚本里面,带参数 [英] using command substitution inside a sed script, with arguments

查看:1285
本文介绍了使用命令替换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.

这篇关于使用命令替换sed脚本里面,带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆