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

查看:37
本文介绍了在 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

(每个之间有换行符;它们会被您的网站格式删除).好吧,该脚本对我有用(输出运行测试"),但显然没有传递给测试的参数.我希望 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 匹配的模式将作为参数提供给 test.我真的没想到上面的方法能奏效,但我已经尝试了我能想到的 $() 括号、反引号和转义符的所有组合,但在任何地方都没有提到这种情况.有帮助吗?

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?

推荐答案

Sed 不会执行命令.但是,Perl 会在正则表达式命令中使用 /e 选项.

Sed won't execute commands. Perl will, however, with the /e option on a regex command.

perl -pe 'sub testit { print STDERR "running test"; return @_[0]; }; s/.*(00).*/testit($1)/e' <testfile.txt

如果您不想看到内联并搞砸输出,请将 stderr 重定向到/dev/null.

Redirect stderr to /dev/null if you don't want to see it in-line and screw up the output.

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

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