1

I have this file:

John Green', 'Age: 32', 'State: New York', 'Total cars: 2', 'Manufacter: General Motor', 'Model: Pontiac', 'Year: 2000', 'Manufacter: Ford Motor', 'Model: Endeavour', 'Year: 2010
Peter Jones', 'Age: 20', 'State: Florida', 'Total cars: 0
Richard Smith', 'Age: 44', 'State: Illinois ', 'Total cars: 1', 'Manufacter: Toyota', 'Model: Yaris', 'Year: 2005
Brian Brown', 'Age: 42', 'State: Texas', 'Total cars: 0
Vincent Osmnod', 'Age: 39', 'State: Maryland', 'Total cars: 1', 'Manufacter: Fiat', 'Model: 500X', 'Year: 2015

I can use awk to extract the 4th field
and if I want to get the number of occurences of ', ' per line I use the script:

grep -o -n "', '" file | cut -d : -f 1 | uniq -c

this command also gives me the number of line

  9 1
  3 2
  6 3
  3 4
  6 5

so I can get the results separately

My desired output is:

Total cars: 2 |9 1
Total cars: 0 |3 2
Total cars: 1 |6 3
Total cars: 0 |3 4
Total cars: 1 |6 5

I tried with this script:

#!/bin/bash
FILENAME=$1
count=0
while read LINE
do
        OUTP1=$(awk -F"', '" '{print $4" |"}' $LINE)
        OUTP2=$(grep -o -n "', '" $LINE1 | cut -d : -f 1 | uniq -c)
        echo "$OUTP1 $OUTP2"
done < $FILENAME

and it gives me this output:

awk: cannot open John (No such file or directory)
       3 1
      6 2
      3 3
      6 4

2 Answers 2

1

Try this:

$ awk -v FS="', '" '{print $4 " |"NF-1 " " NR}' file

If you have blank lines in file, you may want to use:

$ awk -v FS="', '" 'NF >= 1 {print $4 " |"NF-1 " " NR}' file
Total cars: 2 |9 1
Total cars: 0 |3 2
Total cars: 1 |6 3
Total cars: 0 |3 4
Total cars: 1 |6 5

This relies on the use of ', ' as field separator, so if a line ends with that combination of characters the last field will be considered empty. That may be a corner case for you. If so, please, mention it so this and other solutions can be adapted.

0
awk -F "," '{print $4}'"{o=gsub(/', '/,$0);print o,NR}" filename |sed -e  "N;s/\n/|/g" -e "s/'//g"

output

 Total cars: 2|9 1
 Total cars: 0|3 2
 Total cars: 1|6 3
 Total cars: 0|3 4
 Total cars: 1|6 5

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.