Issue
I have a file where each line contains a person's name, occupation, and duties separated by commas. How could I print the name of the people who have a specific occupation? So far i have
awk -v val="barrister" '$0 ~ val' Occupation.txt
for printing the lines that contain the occupation
But I dont know how I could make it so it only prints the line until the first comma.
Solution
Awk
works by applying actions specified within {}
blocks to records
(lines) filtered according to pattern
s (identified within //) that optionally precede action blocks.
Thus, the following command processes lines from occupation.txt
, if they contain the string pattern "barrister", and prints the first field
(column) $1
from those lines. Lines not containing the search pattern are ignored.
(default field separator changed from space to comma, as pointed out by @tshiono)
awk ' BEGIN{FS = ","} /barrister/{print $1}' occupation.txt
equivalent to:
awk -F "," '/barrister/{print $1}' occupation.txt
tested on
occupation.txt
:
John, barrister, early
Jane, barrister, late
Kevin, manager, early
Karen, manager, late
output:
John
Jane
Answered By - Dave Pritlove Answer Checked By - Terry (WPSolving Volunteer)