1

Sample file

wolf@linux:~$ cat file.txt 
Apples
Bananas
Cherries
Dragon Fruit
Elderberry
wolf@linux:~$ 

grep s from the file.txt

wolf@linux:~$ grep s file.txt 
Apples
Bananas
Cherries
wolf@linux:~$ 

Keep it in var

wolf@linux:~$ var=`grep s file.txt`
wolf@linux:~$ echo $var 
Apples Bananas Cherries
wolf@linux:~$ 

Instead of keeping it in horizontal lines like Apples Bananas Cherries, would it be possible to keep data in variable similar to their original format?

Updating the answer and example for future reference

Always use double quotes around variable substitutions and command substitutions: "$foo", "$(foo)"

E.g.

Without double quote

wolf@linux:~$ echo $var
Apples Bananas Cherries
wolf@linux:~$ 

With double quote

wolf@linux:~$ echo "$var"
Apples
Bananas
Cherries
wolf@linux:~$
Wolf
  • 1,631
  • 1
    Does this answer your question? How to get output of variable with line breaks? and also see more in-depth explanation: https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters?noredirect=1&lq=1, especially the part Why do I need to write "$foo"? What happens without the quotes? – pLumo Jul 10 '20 at 11:16

0 Answers0