Quote:
Originally Posted by huge
Basically shell variables are not designed to take newlines.
|
This is simply not true. A variable can contain anything except a null byte. What you have to worry about is that newlines (ascii character 012[octal]) are often considered special syntax by the shell and other commands. The shell processes them as either whitespace or command terminators, and other commands like grep and sed use them as input string delimiters.
Code:
$ variable='foobar
+ foobar
+ foobar'
$ echo "$variable"
foobar
foobar
foobar
$ echo $variable
foobar foobar foobar
Since I didn't quote the variable in the last command, the shell treated the newlines as whitespace and removed them during the word-splitting process. Each word was then passed as a
separate argument to
echo. Double-quoting preserves them as literal newlines.
See her for more on how the shell handles arguments and whitespace:
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes
To change spaces into newlines inside a variable, you can use a simple
parameter expansion.
Code:
$ variable='foobar foobar foobar'
$ echo "${variable// /$'\n'}"
foobar
foobar
foobar
All space characters are simply substituted with newline characters as the variable is expanded. It uses the
$'..' ansi-c quoting form, which expands certain backspace-escaped patterns like
\n (newline) and
\t (tab) into their literal ascii equivalents. See the QUOTING section of the bash man page.
BUT FINALLY, in cases like this, you really should be using an
ARRAY to store the urls, rather than a scalar variable. Then you won't have to worry about dealing with newlines at all.
http://mywiki.wooledge.org/BashGuide/Arrays
http://mywiki.wooledge.org/BashFAQ/005
Assuming you can get your wget/grep command to output a clean list of urls, separated by whitespace of some kind (space-tab-newline), then you set them into an array like this:
Code:
urls=( $( wget.... | grep .... ) )
for i in "${urls[@]}" ; do
mycommand "$i"
done
P.S. @
huge; Please use
[code][/code] tags around your code, to preserve formatting and to improve readability.