代码之家  ›  专栏  ›  技术社区  ›  w00t

将一个命令的输出作为参数传递给另一个命令[重复]

  •  2
  • w00t  · 技术社区  · 14 年前

    我有这个 对于 :

    for i in `ls -1 access.log*`; do tail $i |awk {'print $4'} |cut -d: -f 1 |grep - $i > $i.output; done
    

    LS 将提供access.log、access.log.1、access.log.2等。
    将给出每个文件的最后一行,如下所示: 192.168.1.23 - - [08/Oct/2010:14:05:04 +0300]
    AWK+切割 将提取日期(2010年10月8日-但每个access.log中的日期不同),这将允许我 格雷普 并将输出重定向到单独的文件。

    但我似乎无法将awk+cut的输出传递给grep。

    所有这一切的原因是这些访问日志包含多个日期的行(06/Oct、07/Oct、08/Oct),而我只需要具有最新日期的行。

    我怎样才能做到这一点?

    谢谢您。

    5 回复  |  直到 12 年前
        1
  •  1
  •   mouviciel    14 年前

    作为旁白, tail 显示最后10行。

    可能的解决办法是 grep 这种方式:

    for i in `ls -lf access.log*`; do grep $(tail $i |awk {'print $4'} |cut -d: -f 1| sed 's/\[/\\[/') $i > $i.output; done
    
        2
  •  1
  •   ghostdog74    14 年前

    你为什么不把它分成几步呢??

    for file in *access.log
    do
      what=$(tail "$i" |awk {'print $4'} |cut -d: -f 1)
      grep "$what" "$file" >> output
    done
    
        3
  •  1
  •   Dennis Williamson    14 年前

    你不应该使用 ls 那样。也, ls -l 给你不需要的信息。这个 -f 选择权 grep 将允许您通过管道将图案传送到 格雷普 . 总是引用包含文件名的变量。

    for i in access.log*; do awk 'END {sub(":.*","",$4); print substr($4,2)}' "$i" | grep -f - $i > "$i.output"; done
    

    我也排除了 tail cut 因为awk可以做他们的工作。

        4
  •  0
  •   joni    14 年前

    嗯… 使用xargs或backticks。

    man xargs
    

    http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html 第3.4.5节。命令替换

        5
  •  0
  •   gideonite    12 年前

    你可以试试:

     grep "$(stuff to get piped over to be grep-ed)" file
    

    我没有尝试过,但我在此处应用的答案如下:

     grep "$(for i in `ls -1 access.log*`; do tail $i |awk {'print $4'} |cut -d: -f 1 |grep - $i > $i.output; done)" $i