Shell Script Loop Through List Line by Line

Shell Script Loop Through List Line by Line

I'm trying to write a short shell script to loop through a list (given by a certain command I run) line by line and push values to CSV file

list for example:

aaa   bbb   ccc   ddd   eee   fff
jjj   kkk   lll   mmm   nnn   ooo
uuu   vvv   www   xxx   yyy   zzz

Need to loop through this and for each line take 1st,4rd and 6th fields into variables so I can do some manipulation on them.

#!/bin/sh
#
CSVfile="/tmp/`hostname`.csv"
filter=$( command )
touch $CSVfile
#
for i in $filter
do 

    first=$( printf "$i" | awk {'print$1'})
    fourth=$( printf "$i" | awk {'print$4'})
    sixth=$( printf "$i" | awk {'print$6'})
    cmd=$( cat /home/app/$first/$fourth/out | grep value | awk -F: {'print$2'})
    echo `date +%d%m%Y,%H%M%S`,"$sixth","$cmd" >> $CSVfile

done

The problem here is the for loop goes field by field and not line by line. need each line goes into $i so I can parse it with "awk"

2

1 Answer

This issue has been resolved by using while loop with IFS. Command output stored in variable ($filter) and read line by line by the loop. I could not find a way to push command directly into the loop w/o variable (I believe this is not supported by shell only bash)

#!/bin/sh
#
CSVfile="/tmp/`hostname`.csv"
filter=$( command )
touch $CSVfile
#
while IFS= read -r line
do
    first=$( printf "$i" | awk {'print$1'})
    fourth=$( printf "$i" | awk {'print$4'})
    sixth=$( printf "$i" | awk {'print$6'})
    cmd=$( cat /home/app/$first/$fourth/out | grep value | awk -F: {'print$2'})
    echo `date +%d%m%Y,%H%M%S`,"$sixth","$cmd" >> $CSVfile

done < $filter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.