Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

In a shell script I tried to replace blank space by \n with this command

echo -e $var |tr ' ' '\n'

Outside the script it workd perfectly but inside there is no effect . This how i use in the script:

var =$(echo -e $var | tr ' ' '\n' )

Thanks .

share|improve this question

2 Answers 2

up vote 3 down vote accepted

After expanding a parameter expansion ($var) or command substitution ($(cmd)), the shell removes all whitespace from the expanded result in order to split them into words (word splitting). On top of that, it tries to match filenames for the words that contain *, ? and/or [...] (pathname expansion). So always enclose expansions in double quotes ("$var" and "$(cmd)") to avoid word splitting and pathname expansion to be attempted.

$ var=$'two\nlines   here'
$ echo $var
two lines here
$ echo "$var"
two
lines   here
$

Hence:

echo "$var" | tr ' ' '\n'
# or using bash's more powerful types of parameter expansions
echo "${var// /$'\n'}"

var="$(echo "$var" | tr ' ' '\n')"

See also: http://mywiki.wooledge.org/Quotes

share|improve this answer

From the Bash manual (man bash):

Command substitution allows the output of a command to replace the command name. There are two forms:

$(command)

or

`command`

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

That's why the newline characters are lost.

share|improve this answer

Your Answer

 
discard

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.