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
----
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"
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