I am trying to figure out a way to execute a Linux command only if a specific column in my CSV file has a value greater than 1.

Sample CSV file:


Using the example above, I would like my script to check column 2 of the CSV, and if it finds value > 1 (in this case it would because of the 3) then it would run the command, and if all the values in column 2 were 1, then it would do nothing.

Can somebody help me accomplish this?

  • does the command need to use any of the values in the csv file as args, or does it just have to run once for each line when $2 > 1? – cas Nov 20 '15 at 4:12
  • It just needs to execute the Linux command once for the whole file if it finds one or more instances of a value > 1 in column 2. None of the values in column two are being passed onto the command. – DM-007 Nov 20 '15 at 4:26

awk -F, 'NR>1 && $2 > 1 {found=1 ; exit} ; END {exit !found}' file.csv && mycommand

This exits with 0 (true) if any field 2 is > 1. Otherwise it exits with 1 (false). mycommand is run if true.

The NR>1 skips the Item,Quantity header (the string "Quantity" evaluates to > 1).


Check the columns with awk and exit with some number if they match the criteria. Then test the exit code with $? and run your command(s).

awk -F ',' '$2>1{exit 42}' file
[[ "$?" -eq 42 ]] && echo yes || echo no

if [[ $(cut -d, -f2 file.txt | grep '[0-9]' | sort -nr | head -1) -gt 1 ]]; then
  echo 'a number in the 2nd column is greater than 1.'
  echo 'i am doing nothing.'

This should do it:

if grep -qE ',([2-9]|[1-9][0-9])' file
    echo execute your command
  • This will find values >1 in any column (other than the first), and not just in the second column. – G-Man Says 'Reinstate Monica' Nov 20 '15 at 6:02
  • 1
    As designed. On the file format specified in the question this code yields the correct output. – RobertL Nov 20 '15 at 6:12
  • @RobertL as much as I hate to admit it, you are absolutely correct. Have an upvote to remove that nasty negative score. – rubynorails Nov 20 '15 at 6:56
  • @rubynorails Thank you. I think simple is better. I don't understand why someone (@G-Man?) would downvote something that works correctly. Unnecessary functionality increases the chance of errors (bugs). – RobertL Nov 20 '15 at 7:07

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.