20

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?

0

1 Answer 1

34

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

Not the answer you're looking for? Browse other questions tagged .