0

I'm sorry the title is so convoluted, but I don't know how to explain it better

The context is as follows: imagine a hospital waiting room. Each person who is admitted is given a name, surname, age, identity number, waiting time and priority.

A file, called "patients.txt", is generated with this data:

first_name last_name age identity_number waiting_time_in_seconds priority

(So, there are six columns).

When there are more than 15 patients waiting, a new file (called "priority.txt") should be generated containing those patients with priority 4 and 5.

I know that with if [[ $(wc -l <patients.txt) -gt 15 ]] you can make Bash know when there are more than 15 patients, but how do I establish that ONLY the patients with priority 4 and 5 go to the new file?

Thank you.

1 Answers1

0

Using awk:

awk '$6 == "4" || $6 == "5" { print $0 >> "patients1.txt" }' patients.txt

Check if the 6th space delimited field is 4 or 5. If it is, print th3 line to a new file called patients1.txt

If you want to move the lines to the new file:

awk 'BEGIN { prnt=1 } $6 == "4" || $6 == "5" { print $0 >> "patients1.txt";prnt=0 }prnt' patients.txt >> patients.tmp && mv -f patients.tmp patients.txt

Print lines when not 5 or 6 outputting to a temp file patients.tmp. Move the to file to patients.txt

With more recent versions of awk, you can use the -i flag:

awk -i 'BEGIN { prnt=1 } $6 == "4" || $6 == "5" { print $0 > "patients1.txt";prnt=0 }prnt' patients.txt
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18