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



我得到了一个脚本,可以格式化一些难以阅读的日志文件的输出,使它们可读。 我按如下方式调用我的脚本

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

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

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 '|' '12' |
# 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'
管道 -

| - 接受一个命令的标准输出,并将其"连接"到另一个命令的标准输入。

一个简单的脚本(假设它被称为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变量中。这样,每行都会在循环中打印(在上面的示例中,它也以"行"字为前缀,以将其与常规ls -al输出区分开来(。

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

awk '{print $1}'

可以像以下方式调用:

$ ls -al | ./script.sh
total
drwxr-xr-x+
drwxr-xr-x
-rwxr-xr-x

这表明awk确实在做它的工作 - 它将获取并打印由ls -al生成的输出的每一行的第一个标记($1 |(。


关于 Bash 和 Awk 中$1的说明

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

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也被逃脱了($1(,而 Bash' 的一个没有。

最新更新