【问题标题】:grep and awk, combine commands?grep 和 awk,组合命令?
【发布时间】:2019-06-18 09:49:43
【问题描述】:

我的文件看起来像:

This is a RESTRICTED site.
All connections are monitored and recorded.
Disconnect IMMEDIATELY if you are not an authorized user!
sftp> cd outbox
sftp> ls -ltr
-rw-------   1 0        0            1911 Jun 12 20:40 61N0584832_EDIP000749728818_MFC_20190612203409.txt
-rw-------   1 0        0            1878 Jun 13 06:01 613577165_EDIP000750181517_MFC_20190613055207.txt

我只想打印 .txt 文件名,最好是在一个命令中。

我能做到:

grep -e '^-' outfile.log > outfile.log2

..它只给出以'-'开头的行。

-rw-------   1 0        0            1911 Jun 12 20:40 61N0584832_EDIP000749728818_MFC_20190612203409.txt
-rw-------   1 0        0            1878 Jun 13 06:01 613577165_EDIP000750181517_MFC_20190613055207.txt

然后:

awk '{print $9}' outfile.log2 > outfile.log3

..它给出了所需的输出:

61N0584832_EDIP000749728818_MFC_20190612203409.txt
613577165_EDIP000750181517_MFC_20190613055207.txt

那么问题来了,这2个命令可以合并成1个吗?

【问题讨论】:

  • dos2unix < outfile.log | grep -Po '[^ ]*txt$'
  • 您的文件名曾经是否可以包含空格,例如。 61N0584832 MFC_20190612203409.txt?

标签: unix awk grep


【解决方案1】:

您可以使用单个awk:

awk '/^-/{ print $9 }' file > outputfile

或者

awk '/^-/{ print $9 }' file > tmp && mv tmp file

它是这样工作的:

  • /^-/ - 查找以 - 开头的每一行
  • { print $9 } - 仅打印匹配行的字段 9。

【讨论】:

    【解决方案2】:

    似乎匹配领先的- 并不是你想要的。如果您只想获取 .txt 文件作为输出,请过滤文件名:

    awk '$9 ~ /\.txt$/{print $9}' input-file
    

    【讨论】:

    • 加分 1,因为您能够阅读请求。 I want to print only the .txt file names
    【解决方案3】:

    使用 grep 并启用 PCRE (-P) 标志:

    grep -oP '^-.* \K.*' outfile.log 
    61N0584832_EDIP000749728818_MFC_20190612203409.txt
    613577165_EDIP000750181517_MFC_20190613055207.txt
    

    '^-.* \K.*' :以- 开头的行,直到最后一个空格被匹配但被忽略(\K 左侧的任何内容都将被匹配和忽略),\K 右侧的匹配部分将被打印。

    【讨论】:

      【解决方案4】:

      既然他清楚地写了I want to print only the .txt file names,我们应该测试txt文件,因为文件名总是最新的列,我们只测试最新的文件行来使它更便携:

      awk '$NF ~ /\.txt$/{print $NF}' outfile.log > outfile.log2
      61N0584832_EDIP000749728818_MFC_20190612203409.txt
      613577165_EDIP000750181517_MFC_20190613055207.txt
      

      【讨论】:

        猜你喜欢
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        • 2016-07-31
        • 1970-01-01
        相关资源
        最近更新 更多