[英]bash: awk print with in print
I need to grep some pattern and further i need to print some output within that.我需要 grep 一些模式,而且我需要在其中打印一些输出。 Currently I am using the below command which is working fine.
目前我正在使用下面的命令,它工作正常。 But I like to eliminate using multiple pipe and want to use single awk command to achieve the same output.
但我喜欢消除使用多个管道并希望使用单个 awk 命令来实现相同的输出。 Is there a way to do it using awk?
有没有办法使用awk来做到这一点?
root@Server1 # cat file
Jenny:Mon,Tue,Wed:Morning
David:Thu,Fri,Sat:Evening
root@Server1 # awk '/Jenny/ {print $0}' file | awk -F ":" '{ print $2 }' | awk -F "," '{ print $1 }'
Mon
I want to get this output using single awk command.我想使用单个 awk 命令获取此输出。 Any help?
有什么帮助吗?
Try this尝试这个
awk -F'[:,]+' '/Jenny/{print $2}' file.txt
-F
value inside the [ ]
[ ]
使用多个-F
值+
means one or more since it is treated as a regex. +
表示一个或多个,因为它被视为正则表达式。您可以尝试以下操作:
awk -F: '/Jenny/ {split($2,a,","); print a[1]}' file
For this particular job, I find grep
to be slightly more robust.对于这个特殊的工作,我发现
grep
稍微更健壮。 Unless your company has a policy not to hire people named Eve.除非您的公司有不雇用名为 Eve 的人的政策。 (Try it out if you don't understand.)
(不明白的可以试一试。)
grep -oP '^[^:]*Jenny[^:]*:\K[^,:]+' file
Or to do a whole-word match:或者做一个全字匹配:
grep -oP '^[^:]*\bJenny\b[^:]*:\K[^,:]+' file
Or when you are confident that "Jenny" is the full name:或者当您确信“Jenny”是全名时:
grep -oP '^Jenny:\K[^,:]+' file
Output:输出:
Mon
Explanation:解释:
\\K
speaks for itself: it selects the line(s) with the desired name.\\K
的东西不言自明:它选择具有所需名称的行。[^,:]+
captures the day of week (in this case Mon
). [^,:]+
捕获星期几(在本例中为Mon
)。\\K
cuts off everything preceding Mon
. \\K
切断Mon
之前的所有内容。-o
cuts off anything following Mon
. -o
切断Mon
之后的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.