在 sed 脚本中使用带有参数的命令替换
我正在尝试编写一个简短的脚本,在其中使用 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 匹配的模式作为参数提供给测试。我真的没想到上面的方法会起作用,但我已经尝试了我能想到的 $() 括号、反引号和转义符的所有组合,并且在任何地方都找不到提到这种情况的地方。帮助?
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
where testfile.txt contains:
1234
2345
3006
4567
(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
and output:
running test
00
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
sed 不会执行命令。然而,Perl 将在正则表达式命令上使用
/e
选项。如果您不想看到内嵌的 stderr 并搞砸输出,请将其重定向到 /dev/null 。
Sed won't execute commands. Perl will, however, with the
/e
option on a regex command.Redirect stderr to /dev/null if you don't want to see it in-line and screw up the output.
这可能对您有用:
或者如果您使用 GNU sed:
注意您必须记住首先导出该函数。
This might work for you:
Or if your using GNU sed:
N.B. You must remember to export the function first.
试试这个:
注意:我的正则表达式可能是错误的,但重要的是通过管道传输到 shell (
sh
)try this:
Note: I might have the regex wrong, but the important bit is piping to shell (
sh
)