简体   繁体   中英

Iterate variables in a file to check for a particular value in bash

Below is my requirement. I have a text file that has following content

File name - abc.txt
Content -
apple=0
mango=1
strawberry=10

I need to kick off the subsequent process only if any of the above stated variable has non zero values.

In this case, As two variables have values 1 and 10 respectively, I need to update an indicator - SKIP INDICATOR=N

If all variables have 0 as value, I need to update SKIP INDICATOR=Y

How to achieve this functionality in Linux. Kindly advise.

with very simple greps :

if [ $(grep '=' your_file | grep -v '=0') ]
then 
  echo "non zero values detected"
  SKIP_INDICATOR=N
else
  echo "all are zeroes"
  SKIP_INDICATOR=Y
fi   

Just note that this is a quick and dirty solution and it would NOT work properly if you have for example a=01 or a= 0 (eg with space)

Try:

grep -q '=0*[1-9]' textfile && skip_indicator=N || skip_indicator=Y

=0*[1-9] matches an '=' character followed by zero or more '0' characters followed by a digit in the range 1 to 9.

See Correct Bash and shell script variable capitalization for an explanation of why I changed SKIP_INDICATOR to skip_indicator .

#!/bin/bash
flag=`awk -F'=' '$NF!="0"{print;exit}' input`
if [ ! -z $flag ] ; then
    SKIP_INDICATOR=N
    echo "some variable value is different from 0. do something"
else
    SKIP_INDICATOR=Y
    echo "all variables have 0 as value. do another thing."
fi
exit 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM