I want to read a string from file and print it as follow :
LINE=tr '\n' ' ' < $FILENAME
x1=$LINE
echo $LINE
but the command echo $LINE display an empty line ?
I want to read a string from file and print it as follow :
LINE=tr '\n' ' ' < $FILENAME
x1=$LINE
echo $LINE
but the command echo $LINE display an empty line ?
As already pointed out by the other posters, to embed the output of the tr command into another command (in this case LINE=...), surround the tr command by $(...). In bash this is known as command substitution.
LINE=$(tr '\n' ' ' < "$FILENAME")
In case you intend to use $LINE as a sequence of parameters for subsequent commands (in this case echo), then newlines are eventually replaced by space during word splitting. This would make tr superfluous; you might as well do this:
LINE=$(cat "$FILENAME")
or even better:
LINE=$(< "$FILENAME")
Word splitting is not effective inside double quotes; so echo "$LINE" would still require tr to remove newlines.
$(...) does NOT replace newlines with spaces - the only thing it does is trim trailing newlines (however many). Your alternate solutions therefore do not work as intended. Also, please double-quote the $FILENAME references.$FILENAME has interior newlines, they will end up in the value of $LINE. It is only when you later reference $LINE without quoting that word splitting occurs - along with other shell expansions such as globbing, which may or may not be desired.$LINE be used). OP was not explicit about that, so everybody will have to make up his own mind there.You should be using command substitution like this:
LINE=$(tr '\n' ' ' < "$FILENAME")
But this will store tr's output into LINE variable.
Command substitution has a syntax which is either back-tick OR $(..)$(...) (or backticks), you assign a string literal to LINE. Command substitution means that the string enclosed in $(...) is interpreted as a command and executed, and its result is then assigned to LINE.I think you need to put the call to the tr command with backquotes:
LINE=`tr '\n' ' ' < $FILENAME`
$(...) syntax - the latter has the advantage that it can be nested.