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?

cuonglm
  • 153,898
Fanooos
  • 103

3 Answers3

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.

cuonglm
  • 153,898
-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
cuonglm
  • 153,898
nghnam
  • 129
  • 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 07: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 01:34
-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
PersianGulf
  • 10,850