grep 和 awk,如何组合使用命令?

3
我有一个看起来像这样的文件:
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

所以问题是,这两个命令可以合并成一个吗?

dos2unix < outfile.log | grep -Po '[^ ]*txt$' - Cyrus
你的文件名中是否可以包含空格,例如 61N0584832 MFC_20190612203409.txt - Ed Morton
4个回答

8
您可以使用单独的awk
awk '/^-/{ print $9 }' file > outputfile

或者

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

它的工作原理如下:
  • /^-/ - 查找每一行以 - 开头的内容。
  • { print $9 } - 仅打印匹配行中第9个字段。

3
似乎匹配前导符号-并不是您想要的。如果您只想得到.txt文件作为输出,请过滤文件名:
awk '$9 ~ /\.txt$/{print $9}' input-file

既然您能够阅读请求,那么请加1。我想要打印出仅为 .txt 文件的文件名。 - Jotne

1
使用启用了 PCRE(Perl Compatible Regular Expressions)的 grep 命令(使用 -P 标志):
grep -oP '^-.* \K.*' outfile.log 
61N0584832_EDIP000749728818_MFC_20190612203409.txt
613577165_EDIP000750181517_MFC_20190613055207.txt

'^-.* \K.*' :匹配以-开头的行,直到最后一个空格被匹配但不会被输出(\K之前的部分将被匹配但不会被输出),\K之后的部分将被输出。


1

既然他明确写道我只想打印出.txt文件名,我们应该测试txt文件,由于文件名始终是最新的列,因此我们通过仅测试最新的字段行使其更具可移植性,如下所示:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接