I need to grep some pattern and further i need to print some output within that. 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. Is there a way to do it using 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. Any help?
Try this
awk -F'[:,]+' '/Jenny/{print $2}' file.txt
-F
value inside the [ ]
+
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. Unless your company has a policy not to hire people named 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:
grep -oP '^Jenny:\K[^,:]+' file
Output:
Mon
Explanation:
\\K
speaks for itself: it selects the line(s) with the desired name.[^,:]+
captures the day of week (in this case Mon
). \\K
cuts off everything preceding Mon
. -o
cuts off anything following Mon
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.