Home > Software design >  How to print the first words of lines that contain a specific word?
How to print the first words of lines that contain a specific word?

Time:11-07

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.

CodePudding user response:

grep barrister Occupation.txt | \
  awk -F, '{ print $1 }'

CodePudding user response:

Awk works by applying actions specified within {} blocks to records (lines) filtered according to patterns (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.

awk ' /barrister/{print $1}' occupation.txt

tested on

occupation.txt:

John, barrister, early
Jane, barrister, late
Kevin, manager, early
Karen, manager, late

output:

John
Jane

  • Related