For example suppose we have a file called input.txt which contains

100 John Doe LEC05 12356

132 Carol Bon LEC05 156

122 Cavar Liktik LEC01 136


This command should find everyone in LEC05 and print out their first names in sorted order in a file called output.txt

The command should be a one-line command (with pipes).

I'm not sure how it would be done.

see if LEC05 | find first name at index 1 | sort < input.txt > output.txt

How do I do the see if LEC05 | find first name at index 1 part?

  • I'm not sure of the command I mention in the last line, I want to try that but I don't know what command that would be
    – K Split X
    Jun 14 '17 at 15:37
  • 1
    Two ways: grep LEC05 will work but may have a false positive if someone's creative parents have given you a 'LEC05 Smith' in your roster. awk '$4 == "LEC05" {print [...]}' will work unless you have a 'John Wilkes Booth' in your roster.
    – DopeGhoti
    Jun 14 '17 at 15:40

With awk:

awk '$4 == "LEC05" { print $2 }' /path/to/inputfile | sort > outputfile

With grep and cut:

grep 'LEC05' /path/to/inputfile | cut -f2 | sort > outputfile

More awk-ness

     awk '/LEC05/{ name[$2]++ } END { n = asorti( name,sname ); for ( i in sname ) print sname[i]}' input.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.