Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: variables set to full lines.

On Feb 28, 11:34pm, Jason Zapman II wrote:
} Subject: variables set to full lines.
} I've occasionally wanted to do something like this:
} for line in `cat file` ; do
} 	echo $line >> file1
} done
} where $line is set to a string containing each line in the file, rather
} than each word.
} Is there a way to do this?

Depending on your requirements ...

	while read line; do
		echo $line >> file1
	done < file

This has the drawback that stdin is redirected from "file", so if you
do something inside the loop like

		rm -i $line

then when "rm" prompts for input, it also reads from "file", which is
probably not what you meant.

If you -really- want the entire contents of "file" read into the shell
all at once, this is the way to do it in 3.0.5 and 3.1.x:

	for line in "${(@f)$(<file)}"; do
		echo $line >> file1

The double-quotes are required to preserve newlines in $(<file); the (f)
splits the result into words at newlines; the (@) splits the double-quoted
string into words again.

The same basic trick works in older versions (back to 3.0.0, I think)
but you have to throw in additional ${} to get the parameter substitution
to work correctly, and you probably need a space in the $(< ); I don't
recall exactly, something like

	for line in "${(@)${(f)${$(< file)}}}"; do

Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

Messages sorted by: Reverse Date, Date, Thread, Author