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

print only the pattern in the whole line using grep

据我所知,使用命令 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>

我尝试了很多,但我可以打印出准确的模式 < >

感谢您的帮助!

类似于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?"":" "), [=11=]}'

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>