0

I have a file called indexes.out

The contents below is inside indexes.out file:

informix abc_aseld_idx1
informix abc_aseld_idx2
informix abc_aseld_idx3
informix abc_aseld_idx4
informix abc_aseld_idx5

I want to create a for loop that can pull each line at a time keeping the format. I am using the below for loop command:

for i in `
cat indexes.out`
do
echo "$i"
done

Ouput is:

informix
abc_aseld_idx1
informix
abc_aseld_idx2
informix
abc_aseld_idx3
informix
abc_aseld_idx4
informix
abc_aseld_idx5
informix

I want to see the same output as file, because I want to work with both columns in the loop at a later point working with awk $1 and $2:

informix abc_aseld_idx1
informix abc_aseld_idx2
informix abc_aseld_idx3
informix abc_aseld_idx4
informix abc_aseld_idx5

Once in the loop, I want to then use each row to filter on specific columns individually.

2 Answers2

0

By default, a for-loop loops over words, not lines!

Normally, there is no need for a loop and you would just use awk as it is exactly doing this, looping through lines of file:

awk '{print $1,$2 ;}' indexes.out

If you want to go on working with the data in the shell, you can use a while loop and read:

while read a b; do echo "$a $b"; done < indexes.out

For other uses, you should refer to this related question.

pLumo
  • 22,565
-2

I found a work around that will work for me:

Instead of using a space in the file use a delimiter pipe (|) as below:

informix|abc_aseld_idx1
informix|abc_aseld_idx2
informix|abc_aseld_idx3
informix|abc_aseld_idx4
informix|abc_aseld_idx5

Once in loop you can replace pipe with spacing like below:

for i in `cat indexes.out`
do
echo "$i" | sed 's/|/ /g
done 

output is:

informix abc_aseld_idx1
informix abc_aseld_idx2
informix abc_aseld_idx3
informix abc_aseld_idx4
informix abc_aseld_idx5
  • Instead of using an ugly workaround (the pipe) for the downsides of a wrong solution (for loop in processing text), it would be better to think about what you actually need, and to find a good solution for that. You already got one answer for the question you posed, and you would have received other answers, if you'd told up front what you actually want. Here, you're just outputting the data, and to do that, you could just cat indexes.out on the original file, without the space-to-pipe transformation – ilkkachu Jul 19 '19 at 09:08