bash sed/awk:从文本流中提取模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6938087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:50:04  来源:igfitidea点击:

sed/awk: Extract pattern from text stream

bashsedawkgrep

提问by Dagang

2011-07-01 ... /home/todd/logs/server_log_1.log ...
2011-07-02 ... /home/todd/logs/server_log_2.log ...
2011-07-03 ... /home/todd/logs/server_log_3.log ...

I have a file looks like the above. I want to extract the file names from it and output to STDOUT as:

我有一个看起来像上面的文件。我想从中提取文件名并输出到 STDOUT 为:

server_log_1.log
server_log_2.log
server_log_3.log

Could someone help? Thanks!

有人可以帮忙吗?谢谢!

The file name pattern is server_log_xxx.log, and it only occurs once in a line.

文件名模式是 server_log_xxx.log,它在一行中只出现一次。

回答by glenn Hymanman

Assuming the "xxx" placeholder is only digits:

假设“xxx”占位符只是数字:

grep -o 'server_log_[0-9]\+\.log'

回答by Pawe? Nadolski

Pipe your file through following command:

通过以下命令管道您的文件:

sed 's/.*\(server_log_[0-9]\+\.log\).*//'

回答by Zsolt Botykai

With awk and your input pattern:

使用 awk 和您的输入模式:

awk 'BEGIN {FS="/"}
     { print gensub(" .*$","","g",) }' INPUTFILE

See it action here: https://ideone.com/kcadh

在此处查看操作:https: //ideone.com/kcadh

HTH

HTH

回答by Dimitre Radoulov

sed 's|.*/\([^/ ]*\).*||' infile