Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a file with colon-separated strings

Tags:

bash

loops

awk

I have a file that looks like this:

work:week:day:england:
work1:week:day:sweden:
work2:week:day::
..... 

Each time I loop through the list I want go get each string as a variable which I can use. E.g if I want to know which location I work in I would get the fourth location column from the first column "work*"

I tried this:

for country in $( awk -F '[:]' '{print $1}' file.txt); do
    if [[ "$country" == "england" ]];
    then
            echo "This user works in England!"
    else
            echo "You do not work in England!"
    fi
done

I would like to get each strings separated by a colon as a variable for each row each loop.

like image 647
Kevin Avatar asked Mar 02 '26 19:03

Kevin


2 Answers

You can use just bash for this: set IFS (internal field separator) to : and this will catch the fields properly:

while IFS=":" read -r a b c country
do
  echo "$country"
done < "file"

This returns:

england
sweden

This way you will be able to use $a for the first field, $b for the second, $c for the third and $country for the forth. Of course, adapt the number and names to your requirements.

All together:

while IFS=":" read a b c country
do
   if [[ "$country" == "england" ]]; then
      echo "this user works in England"
   else
      echo "You do not work in England"
   fi
done < "file"
like image 118
fedorqui 'SO stop harming' Avatar answered Mar 05 '26 08:03

fedorqui 'SO stop harming'


Just do the whole thing in awk:

awk -F: '$4=="england"{print "this user works in England";next}
         {print "You do not work in England"}' file

Set the field separator to a colon. If the fourth field is "england", print the first message. next skips to the next line. Otherwise, print the second message.

The fields on each line are accessible by $1, $2, etc. so you can use the data in each field within awk to do whatever you want. The field is read line by line automatically, so there's no need to write your own while read loop.

like image 23
Tom Fenech Avatar answered Mar 05 '26 08:03

Tom Fenech