4
var  = "a common string \n $var"

I am passing this var to some other method and I am printing var in that other method.i am not able to edit that other method. So echo -e and printf statements cannot be used by me. But I need that \n to be printed as new line instead of that exact literal.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
ayifos
  • 65
  • 1
  • 6
  • `var = "a common string \n $var"` is not a correct way to assign a variable. Also, how are you printing the var in the other method? – fedorqui Oct 04 '16 at 10:03
  • Thanks for the prompt response.I don't know how to append a common string followed by a new line to the existing variable and that is my question. In that new method we are just using echo statement only – ayifos Oct 04 '16 at 10:05
  • See: [How can I have a newline in a string in sh?](http://stackoverflow.com/q/3005963/1983854) or [Trying to embed newline in a variable in bash](http://stackoverflow.com/q/9139401/1983854). – fedorqui Oct 04 '16 at 10:08

2 Answers2

4

If you are setting var in shell script you can actually use printf as follows:

var=$(printf "a common string\n%s" "$var")

or, in newer bash

printf -v var "a common string\n%s" "$var"

If your shell supports the $'…' construct, you can do this instead:

var=$'a common string \n'"$var"
Eric
  • 1,431
  • 13
  • 14
0

Treat the variable as a list with '\n' delimiter so you can go over it in a loop and print each item on it in a new line, something like:

for item in $var; do 
  echo $item
done
yorammi
  • 6,272
  • 1
  • 28
  • 34