0

I have a file that contains about 800 lines. All the lines contains 1 * character in it.

I need to loop through the lines in the file so I used the following simple for loop

for i in $(cat file_path); do echo $i; done

Unfortunately it did not work.

When I try it with another files but the lines in the file do not contains the * character, the loop is working fine.

How can I solve this?

-2

You have to use the following format :

#!/bin/bash
SAVEIFS=$IFS
while IFS= read -r line <&3
do
    echo "$line"
done 3< myfile.txt
IFS=$SAVEIFS

Test is :

root@debian:/home/mohsen/test/shell# ./linebylibe.sh 
ff
dd
gg
tt
tt
ww
ee

And my myfile.txt is :

root@debian:/home/mohsen/test/shell# cat myfile.txt 
ff
dd
gg
tt
tt
ww
ee
  • This will fail if line contains backslash characters. – cuonglm May 13 '15 at 7:53
  • I updated. my answer. – PersianGulf May 13 '15 at 8:05
  • 1
    That still fails for lines containing backslashes or beginning or ending in blanks or lines like "-n", "-nene". See @cuonglm's for the correct answer. – Stéphane Chazelas May 13 '15 at 9:14
  • I solved with $IFS variable. – PersianGulf May 13 '15 at 10:56
  • 2
    It doesn't solve the problem, please see all great explain from @StéphaneChazelas's answer which I referred in my answer. – cuonglm May 13 '15 at 14:57
5

You have some troubles with your code:

You can fix them by using while loop:

while IFS= read -r line <&3; do
  { printf '%s\n' "$line"; } 3<&-
done 3< file

[ -z "$line" ] || printf %s "$line"

A note that using while loops to process text files is considered bad practice in POSIX shell.

-1

You can use while:

while read line; do echo "$line"; done < test.txt

or define separate character IFS:

SAVEIFS=$IFS; IFS="\n"; for i in $(cat test.txt); do echo "$i"; done; IFS=$SAVEIFS
  • This will fail if line contains backslash characters, leaving command substitution unquote is very dangerous and actually doesn't show the OP's issue. You should also save IFS and restore it after the loop. – cuonglm May 13 '15 at 7:54
  • Your for loop still fail when line contains *, that's the same as OP's problem. And setting IFS="\n" is wrong, it set IFS to \ and n, not a newline. – cuonglm May 14 '15 at 1:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.