![]() |
for, cat, and echo
This is something I am curious about. I tried these commands and
expected one behavior but received another. Can anyone explain further? Conditions: I have a file on my computer with the following contents: :
Now is the timeExpected Behavior(this doesn't really happen, but I wish it did): :
for i in `cat file_1`; do echo $i; doneActual Behavior(this is what really happens): :
for i in `cat file_1'; do echo $i; doneI just don't understand why it is putting each word on a different line. Can anyone acheive the expected behavior? What am I doing wrong? -Bryan |
By the way I posted this same thing on alt.comp.lang.shell.unix.bourne-bash about four days ago and no replies. I guess that place is dead.
|
Echo by default outputs a newline character at the end of what you input. According to the man page, you can use the -n option to prevent this. Try changing your second statement to "do echo -n $i;". Note however that spaces are removed when doing a for, so you will have to re-add them.
My solution which is likely against every bash coding guideline in existance: :
for i in $(cat cat_file_1); do echo -n $i; echo -n ' '; done; echoThe last echo is to add a newline to the end. |
for loops are not used to read whole lines of text input, normally. This is because you get wierdness with IFS when you try to set it to newline.
The reason is that for reads fileds as separated by a space rather than a whole record like the read command does. Try playing with IFS try this: :
#! /bin/ksh |
Thanks jim mcnamara for the great response. I think I will start using that read statement from now on. When running the for loop with IFS="\n" I do in fact get really strange results.
:
#!/bin/bashMy results look really nice using read and really weird using for i in `echo file`.... :
now is the time for |
I might be wrong, but wouldn't you want IFS="\\n" because your looking for \n as the line terminator. And for it to read that it needs the extra \ or am I just losing my mind here?
|
Quote:
|
Wouldn't there be an extra round of substitution anyway? This would mean using \\n was equivalent to \n, so you'd still be as well to save a byte, but I think you'd end up with a newline as the field separator either way. Keeping track of quoting and substitution is the main reason you'll rarely see me outside of tclsh. I'm too stupid for bash.
|
| All times are GMT -5. The time now is 4:31 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC