使用grep仅打印整行中的模式

时间:2017-11-03 06:37:47

标签: regex awk grep gawk

据我所知,只使用命令grep -o打印模式。 我有一个这样的文件:

Job <472971> Job Name <aaaaaaaaaaa> User <bbbbbbbbb> Project <cccccc> Status <RUN> Queue <AL_Ptime>Interactive pseudo-terminal shell mode Submitted from host <lsf_login07> CWD </asdfghjklll/dsadasd/asda>

我想在< >内打印出所有模式,我的愿望输出如下:

<472971> <aaaaaaaaaaa> <bbbbbbbbb> <cccccc> <RUN> <AL_Ptime> <lsf_login07> </asdfghjklll/dsadasd/asda>

我尝试了很多,但我可以打印出完全模式< >

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

类似于grep -oE '<[^>]+>'

$ echo "Job <472971> Job Name <aaaaaaaaaaa> User <bbbbbbbbb> Project <cccccc> Status <RUN> Queue <AL_Ptime>Interactive pseudo-terminal shell mode Submitted from host <lsf_login07> CWD </asdfghjklll/dsadasd/asda>" \
| grep -oE '<[^>]+>'
<472971>
<aaaaaaaaaaa>
<bbbbbbbbb>
<cccccc>
<RUN>
<AL_Ptime>
<lsf_login07>
</asdfghjklll/dsadasd/asda>

如果你想摆脱换行符并在两者之间有空格,你可以将它管道化为一个简单的 awk ,如下所示:

grep -oE '<[^>]+>' |  awk '{printf "%s%s", (NR==1?"":" "), $0}'

tr

grep -oE '<[^>]+>' | tr "\n" " "

编辑: 假设OP使用带有多个这些行的输入文件,可以转为GNU awk

$ cat tst.awk
BEGIN { FPAT="<[^>]+>" }
{ for (i=1; i<=NF; i++) printf "%s%s", (i==1?"":" "), $i
  printf "\n"
}

使用它:

awk -f tst.awk file

文件是:

$ cat file
Job <472971> Job Name <aaaaaaaaaaa> User <bbbbbbbbb> Project <cccccc> Status <RUN> Queue <AL_Ptime>Interactive pseudo-terminal shell mode Submitted from host <lsf_login07> CWD </asdfghjklll/dsadasd/asda>
Job <472971> Job Name <aaaaaaaaaaa> User <bbbbbbbbb> Project <cccccc> Status <RUN> Queue <AL_Ptime>Interactive pseudo-terminal shell mode Submitted from host <lsf_login07> CWD </asdfghjklll/dsadasd/asda>

或者,作为一个单行:

$ awk 'BEGIN{FPAT="<[^>]+>"} \
        {for (i=1; i<=NF; i++) printf "%s%s", (i==1?"":" "), $i; printf "\n"}' file
<472971> <aaaaaaaaaaa> <bbbbbbbbb> <cccccc> <RUN> <AL_Ptime> <lsf_login07> </asdfghjklll/dsadasd/asda>
<472971> <aaaaaaaaaaa> <bbbbbbbbb> <cccccc> <RUN> <AL_Ptime> <lsf_login07> </asdfghjklll/dsadasd/asda>