How to loop around the contents of file?

Hi ,
I need to print the contents of a file in a loop
I tried like below but didn't get the contents in the output
The file nms.txt has some names like
apple
grapes
---

#!/bin/ksh
file_nm="/etc/nms.txt"
for data in "echo {$file_nm}"
 do
  echo "$data"
done

The above code gives me the output as

echo {/etc/nms.txt}

I want the output in the echo as
apple
grapes
----

Please suggest me

for data in $(cat $file_nm)

change the for code as follows :-

for data in `echo {$file_nm}`  do   echo "$data" done

Use while loop instead of for lop..

file_nm="/etc/nms.txt"
while read data
do
echo $data
done<$file_nm

I tried both the solution which have been posted .
I'm not getting the contents of the file
I'm usng KSH and getting the following output

#!/bin/ksh
file_nm="/etc/nms.txt"
for data in `echo {$file_nm}`
 do
  echo "$data"
done

./fnm_test.sh
{/etc/nms.txt}

I want the output should be
apple
grapes
-----

Thank you

IFS=""; for i in $(cat $file)
do
        echo $i
done

Have you tried with while loop..?
Check my post.

1 Like

Yes,
I'm able to get the output now. Thank You
Now i had an issue with If condition inside loop
I tried like below and getting error : not found

file="/etc/nms.txt"
chek="ABCD"
# while loop
while read line
do
        # display line or do somthing on $line
        echo "$line"
         if ["$chek" == "$line" ]
           then
            echo "Equal"
         fi
done <"$file"

Where i'm doing wrong here. Please advice

Please put space between square brackets.

like

if [ "$chek" == "$line" ]

Try this,

file_nm="/etc/nms.txt"
mLine="ABCD"
cat $file_nm|while read line
do
echo $line
            if [ $mline == $line ]
            then
                  echo $mLine
            fi
done

This should solve your purpose

Because of field splitting, this will loop over words, not lines.

This doesn't even read the file. It merely echoes the file name, possibly breaking it into pieces if it contains whitespace, then echoes the pieces of the file name. Not a single line of the file's contents is read.

This won't loop over the lines of the file. The entire file's contents will be assigned en masse to i and the loop will iterate at most once (if the file is empty, it won't iterate at all). A functional equivalent:

i=$(cat $file)
[ "$i" ] && echo "$i"

By far the best suggestion, but it's still inadequate for arbitrary text ("arbitrary" being the operative word).

To preserve leading and trailing whitespace, IFS should be unset in read's environment.

To prevent backslashes from being treated specially, read's raw mode should be used.

echo is unsuitable for printing arbitrary text. echo does not support -- to signal the end of option processing. If the arbitrary text looks like a valid option, the output will be mangled. printf should be used instead.

Finally, $data should be quoted to preserve its whitespace.

while IFS= read -r data; do
    printf '%s\n' "$data"
done

Regards,
Alister