Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

I am trying to run a for loop for file and I want to display whole line. But instead its displaying last word only. I want the complete line.

for j in `cat ./file_wget_med`

echo $j


result after run:


Here is my data:

$ cat file_wget_med
2013-09-11 14:27:03 ERROR 404: Not Found.
share|improve this question

2 Answers 2

for loop splits when it sees any whitespace like space, tab, or newline. So, you should use IFS (Internal Field Separator):

IFS=$'\n'       # make newlines the only separator
for j in `cat ./file_wget_med`

echo "$j"

share|improve this answer
And put care about single quotes on IFS because IFS=$"\n" will split also "nn" strings. I found set IFS more reliable than use more complicated syntax or functions. – erm3nda Aug 25 at 4:08
apparently it is advised to unset IFS afterwards, so that other commands are not influenced in this same shell. – Boris Däppen Oct 8 at 14:49

for loops split on any whitespace (space, tab, newline) by default; the easiest way to work on one line at a time is to use a while read loop instead, which splits on newlines:

while read i; do echo "$i"; done < ./file_wget_med

I would expect your command to spit out one word per line (that's what happened when I tested it out with a file of my own). If something else is happening, I'm not sure what could be causing it.

share|improve this answer
This is also a good alternative to for i in `ls`; do echo $1; done, by piping the output to the while command: ls|while read i; do echo $i; done. This works on file/folder names with spaces, without needing to change environment variables. Very good answer. – jishi Jun 1 at 21:23
the while didn't handle the first and last lines very, not as well as the for loop with IFS – Grant Bowman Jul 28 at 15:16
@jishi Since it's primarily designed for display, and is responsive to terminal-window size and such, ls is not considered safe for use with | (the pipe operator). find is more flexible in addition to being safer for this purpose. – SeldomNeedy Nov 20 at 21:48
@GrantBowman Depending on how the file is delimited, it might work better if you try while read -r i instead of just while read i. – SeldomNeedy Nov 20 at 21:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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