在bash或shell中管道映射到哪个参数?

时间:2016-02-10 21:27:03

标签: bash shell pipe sh

我有一个脚本可以格式化一些难以阅读的日志文件的输出,使它们具有人类可读性。我将脚本调用如下

me@myHost $ cat superBigLogFile$date | grep "Stuff from log file I want to see" | /scripts/logFileFormatter

在脚本中,它使用$ 0,$ 1和$ 2,但我不知道cat&#ed; ed文本映射到哪个参数。我想对脚本进行更改,我只需要输入日期和我想要查看的内容。如:

me@myHost $/scripts/logFileFormatter 2016-02-10 "Stuff I want to see"

以下是脚本的详细信息。技术细节是该脚本将NDM日志的输出格​​式化为人类可读的形式。

PATH=/usr/xpg4/bin:/usr/bin
# add SUMM field and end of record marker on stat lines
awk '{print $0"|SUMM=N|EOR"}' |\
# format the STAT file, putting each field on a separate line
tr '|' '\012' |\
# separate times from dates and reformat source and destination file fields
# to have a space after the =
awk -F= '{
    if ($1=="DFIL" || $1=="SFIL") print $1 "= " $2
    else if ($1=="STAR" || $1=="SSTA" || $1=="STOP" ) {
      split($2,A," ")
      print $1 "=" A[1] "=" A[2]
    }
    else print
}' |\
# execute the ndmstat.awk that comes with Connect:Direct
awk -F= -f /cdndm/cmddbp1/cdunix/ndm/bin/ndmstat.awk |\
# additional formatting to remove the greater than sign arrows
sed 's/=>/=/g'

1 个答案:

答案 0 :(得分:4)

管道 - | - 获取一个命令的标准输出,并将其“连接”到另一个命令的标准输入。

一个简单的脚本(我们假设它被称为script.sh):

while read line
do
        echo "line" $line
done

可以像这样工作:

$ ls -al | ./script.sh
line total 15752
line drwxr-xr-x+ 106 kls staff 3604 Feb 10 23:13 .
line drwxr-xr-x 6 root admin 204 May 23 2015 ..
line -rwxr-xr-x 1 kls staff 56 Feb 10 23:13 a.sh

这里的关键部分是read命令,它从标准输入读取并将结果逐行放入line变量中。通过这种方式,每一行都被打印出来(在上面的一个例子中,它还带有一个“line”字样,以便在循环中区分它与常规的ls -al输出)。

现在,我没有测试数据来运行你的脚本,但它与awk非常相似。考虑这个脚本(保存到script.sh):

awk '{print $1}'

可以像:

一样调用
$ ls -al | ./script.sh
total
drwxr-xr-x+
drwxr-xr-x
-rwxr-xr-x

这表明awk确实在做它的工作 - 它会占用并打印$1生成的每行输出的第一个标记(ls -al)(通过标准输入传递 - {{1 }})。

关于Bash和Awk中|的说明

重要提示:$1这里不是Bash变量 - 它是在awk中定义的变量。它并不像在Bash中那样意味着“脚本的第一个参数”,而是“输入中的第一个标记”。这两个是完全独立的 - 这显示了如何同时使用它们:

$1

script.sh

输出:

awk "{print \"$1 \" \$1}"
              ^       ^
              |       |
            Bash     Awk

起初可能有点奇怪,所以我在代码中添加了一些注释。仔细检查双引号,以及如何使用$ ls -al | ./script.sh PREFIX <-- We pass PREFIX now that will be bound to $1 Bash variable. PREFIX total PREFIX drwxr-xr-x+ PREFIX drwxr-xr-x PREFIX -rwxr-xr-x 符号进行转义。同样。 Awk \也会被转义($1),而Bash'则不会。{/ p>