Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I have a bash script. If I run this command to:

  1. grep for certain patterns,
  2. transform the output,
  3. sort the output
  4. dedupe the output

then I get one grep find per line in terminal

LC_ALL=C grep -o --color -h -E -C 0 -r "$pattern" /pathto/Pre_N/ | tr -d '[:digit:]' | sort | uniq

However, if I put it in an output variable then the formatting is lost (upon echoing to a file or echoing on screen).

#!/usr/bin/env bash
output=$(LC_ALL=C grep -o --color -h -E -C 0 -r "$pattern" /pathto/Pre_N/ | tr -d '[:digit:]' | sort | uniq)
echo $output > $fn

How can I preserve the formatting of the out put of this command once I save it to a variable?

share|improve this question

marked as duplicate by Gilles Jul 29 at 21:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

Use quotes :

echo "$output" > $fn

the echo line is parsed by the shell (after variable expansion), and all spaces chars between parameters are reduced to a simple space. As example :

$ var1="toto
> titi
> tutu
> "

$ echo $var1
toto titi tutu

$ echo "$var1"
toto
titi
tutu
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.