Home > Back-end >  Write a Bash script that can print if the number in the last column is odd or even?
Write a Bash script that can print if the number in the last column is odd or even?

Time:06-19

I wanna Write a Bash script that can print if the number in the last column is odd or even or if no numbers in the line from a text file, the data is looking like this in a db.txt file :

sdn sddjk@gmail 123
ksd 234
sddd sddsd@gmail 

i tried this :

#!/bin/bash
input="db.txt"
while IFS=" " read -r rec_column3
do
if [ $((number % 2)) -eq 0 ]; then 
    echo even
elif [ $((number % 2)) -eq 1 ]; then 
    echo odd
elif [[ "$rec_column3" != "number" ]]; then
    echo not number
else 
    echo not found 
fi     
done

output is :

even
even

so can anyone helps me ? tnx

CodePudding user response:

#!/bin/bash
input="db.txt"
#########################
# check third field 
#########################
echo "check third field"
while read -r _ _ rec_column3 
do
  if [[ -z "$rec_column3" ]]; then
    echo "not found" >&2;
  elif ! [[ $rec_column3 =~ ^[0-9] $ ]] ; then
    echo "'$rec_column3' is not a number" >&2;
  elif [[ $((rec_column3 % 2)) -eq 0 ]]; then 
    echo "'$rec_column3' is even" >&2
  else 
    echo "'$rec_column3' is odd" >&2
  fi     
done < $input

echo "-----------------------"

#########################
# or check last field
#########################
echo "check last field"
while IFS=' ' read -r -a array  
do
  last_column=""
  [[ ${#array[@]} -ne 0 ]] && last_column=${array[-1]}
  if [[ -z "$last_column" ]]; then
    echo "not found" >&2
  elif ! [[ $last_column =~ ^[0-9] $ ]] ; then
    echo "'$last_column' is not a number" >&2
  elif [[ $((last_column % 2)) -eq 0 ]]; then 
    echo "'$last_column' is even" >&2
  else 
    echo "'$last_column' is odd" >&2
  fi     
done < $input

$ cat db.txt 
sdn sddjk@gmail 123
ksd 234
ksd 
12345

sddd sddsd@gmail 234 
sddd sddsd@gmail 111 
sddd sddsd@gmail aaa 

$ ./script.sh 
check third field
'123' is odd
not found
not found
not found
not found
'234' is even
'111' is odd
'aaa' is not a number
-----------------------
check last field
'123' is odd
'234' is even
'ksd' is not a number
'12345' is odd
not found
'234' is even
'111' is odd
'aaa' is not a number

CodePudding user response:

awk is probably a better tool for this job. You can do something like this

awk 'BEGIN {split("even odd", a)} $NF ~ /^[0-9] $/ {print a[$NF%2 1]; next} {print "NAN"}' db.txt

Checks if the last field is odd or even (the 1 is because the array a is 1-based).

  • Related