我如何通过shell命令的输出与SED,AWK或更换这样一个子? [英] How do I replace a substring by the output of a shell command with sed, awk or such?

查看:137
本文介绍了我如何通过shell命令的输出与SED,AWK或更换这样一个子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 SED 或命令行工具,通过shell命令的输出,以取代线的部分。例如:

I'd like to use sed or any command line tool to replace parts of lines by the output of shell commands. For example:


  • 将人类可读的时间戳,通过调用替换Linux的时代日期

  • 将其德codeD同行替换特定的协议报文的六场,通过调用一个内部的德codeR

SED 似乎最符合,因为它允许匹配模式和重新其他的一些东西,比如走动匹配位,但不是强制性的。

sed seems best fitted because it allows to match patterns and reformat other things too, like moving bits of matches around, but is not mandatory.

下面是一个简单的例子:

Here is a simplified example:

echo "timestamp = 1234567890" | sed "s/timestamp = \(.*\)/timestamp = $(date -u --d @\1 "+%Y-%m-%d %T")/g"

当然, $(...)的东西不起作用。据我了解,这对环境变量。

Of course, the $(...) thing does not work. As far as I understand, that's for environment variables.

所以会正确的语法是什么?建议 SED 在这种情况下?我花了几个小时的搜索中... SED 甚至能这样?是否有其他工具更适合?

So what would the proper syntax be? Is sed recommended in this case ? I've spent several hours searching... Is sed even capable of this ? Are there other tools better suited?

修改

我需要...


  • 模式匹配。该日志已满其他的事情,所以我需要能够(之前和之后的文本,在同一行)要找准我想替换基于上下文的字符串。这不包括基于列的位置匹配,比如的awk'{$ 3 ...

  • 在就地更换,使得行,时间戳=也好,的reste保持不变。这exclused的sed的'E'命令。

推荐答案

要运行 SED 外部命令,你需要使用电子。看一个例子:

To run an external command in sed you need to use e. See an example:

$ echo "timestamp = 1234567890" | sed "s#timestamp = \(.*\)#date -u --d @\1 "\+\%Y"#e"
2009

通过完整的格式为:

$ sed "s#timestamp = \(.*\)#echo timestamp; date -u --d @\1 '\+\%Y-\%m-\%d \%T'#e" <<< "timestamp = 1234567890"
timestamp
2009-02-13 23:31:30

这捕获时间戳,并将其转换成 +%Y 格式。

This catches the timestamp and converts it into +%Y format.

男人SED

电子

该命令允许一个从shell命令进入管道输入
  模式空间。如果替换作出的命令被发现
  在图案空间执行和图案空间被替换其
  输出。尾随的换行符是燮pressed;结果是不确定的,如果
  要执行的命令包含NUL字符。这是一个GNU SED
  扩展。

This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a nul character. This is a GNU sed extension.

不过,你看这是一个有点丑。根据你想要做什么,你最好使用普通的,而循环来获取值,然后用日期正常。例如,如果该文件是这样的:


However, you see it is a bit "ugly". Depending on what you want to do, you'd better use a regular while loop to fetch the values and then use date normally. For example, if the file is like:

timestamp = 1234567890

然后,你可以说:

Then you can say:

while IFS="=" read -r a b
do
  echo "$b"
done < file

这会让你有 $ B 作为时间戳,然后你可以执行日期...

this will make you have $b as the timestamp and then you can perform a date ....

这篇关于我如何通过shell命令的输出与SED,AWK或更换这样一个子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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