运行时命令的每个输出的前缀


16

我正在尝试制作模块化脚本。我有几个从单个脚本中调用的脚本/命令。
我想给每个单独的命令的输出加上前缀。

考试:

我的文件是allcommands.sh / command1.sh / command2.sh

command1.sh输出
file exists
file moved

command2.sh输出
file copied
file emptied

allcommands.sh运行脚本command1.shcommand2.sh

我想为这两个脚本的每个输出加上前缀:
[command1] file exists
[command1] file moved
[command2] file copied
[command2] file emptied


尝试运行通过它传递的每个命令sed "s/\^/command1 /"
j_kubik 2013年

请给我一个例子,说明我提供的信息。我不太了解sed功能。对不起。
伊万·多科夫

Answers:


21

我假设您在allcommands.sh中所做的是:

command1.sh
command2.sh

只是与它

command1.sh | sed "s/^/[command1] /"
command2.sh | sed "s/^/[command2] /"

9

的最小示例allcommands.sh

#!/bin/bash
for i in command{1,2}.sh; do
    ./"$i" | sed 's/^/['"${i%.sh}"'] /'
done

command1.shcommand2.sh可执行文件一起,并在同一目录中echo查找所需的字符串,这给出了shell输出:

$ ./command1.sh 
file exists
file moved
$ ./command2.sh 
file copied
file emptied
$ ./allcommands.sh 
[command1] file exists
[command1] file moved
[command2] file copied
[command2] file emptied

快速sed故障

sed 's/^/['"${i%.sh}"'] /'
  • s/ 进入“正则表达式模式匹配和替换”模式
  • ^/ 表示“匹配每一行的开头”
  • ${i%.sh}发生在shell上下文中,意思是“ $i,但是去掉后缀.sh
  • ['"${i%.sh}"'] /首先打印a [,然后退出带引号的上下文以$i从shell 抓取变量,然后重新输入以和结束]

感谢您的澄清。您的回答确实很有帮助,但是@j_kubik的示例只是我需要的示例。
伊万·多科夫
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.