bashshell

Bash: Compare each line in for loop


I have a shell script that needs to analyze data from a file which looks like the following:

255  48  48             exp1
97  97  97              exas
238  44  44             dkopkw
194 194 194             sdkaok

I then take the data and sort it in a for statement. For each line I need to compare the data and see if it is less than 90 and prints a line between the numbers.

  #!/bin/bash

  for line in "$(sort /myfile.txt -k1 -n)"
  do

    COL_ONE=$(print "line" | awk '{print $1}')

    if [[ $COL_ONE -lt 90 ]]; then
            echo "$line"
            echo "------------------"
    else 
            echo "$line"
    fi

done

However, when this runs it does not print the line between the numbers. I want my output to look like the following:

97  97  97              exas
------------------------------
194 194 194             sdkaok
238  44  44             dkopkw
255  48  48             exp1

I am not sure what I am doing wrong and it has been driving me insane.


Solution

  • A solution that bypasses the problems with your attempt and is more robust and efficient:

    sort -k1,1 -n myfile.txt | awk '$1 < 98 { print $0 "\n------------------"; next } 1'
    

    Note that I've used 98 rather than 90 as the comparison value, to be consistent with your desired output.
    Also, note the ,1 added to -k1 to ensure that sorting is truly limited to the 1st field.


    As for what you've tried:

    Leaving efficiency issues, the 98 vs. 90 issue, and ill-advised practices aside: