alan alan - 4 months ago 9
Linux Question

for i in `cat file` give variable with space

I am using

for i in `cat file`


to write a loop. However, in the file, the data will be:

A X
B Y
C Z


Is that possible I can give variable $i as:

$i = A X
$i = B Y
$i = C Z


This loop below will only give me variable splited by each space.

for i in `cat file` ; do
echo $i
done;

Answer

This is covered by Bash FAQ 001; don't use a for loop for this.

while IFS= read -r i; do
    echo "$i"
done < file

read ensures you get a full line of text from the file to assign to i; quoting $i ensures that you reproduce the value exactly.