16

Consider the following echo command:

 echo -e "at\r"

which produces the output at on the command line, i.e. the \r special character has been interpreted. I want to do the exact same thing with some text in a file. Supposing the exact same sequence

at\r

is written to a file named at.txt, then I want to display it on the terminal. But

cat at.txt

gives the output

at\r

what is not what I want. I want the special sequence \r to be interpreted, not just printed on the terminal. Anyone any idea?

Thanks Alex

4
  • 1
    Would echo -e "$(cat file)" work? (For small files)
    – knittl
    Commented Aug 29, 2012 at 9:58
  • 2
    Or if the file is very large you could try xargs: cat file | xargs echo -ne Commented Aug 29, 2012 at 10:02
  • The first suggestion works (knittl), the second suggestion (Lee) produces a string 'atr'.
    – Alex
    Commented Aug 29, 2012 at 10:13
  • It seems that xargs uses \ as a special character. To fix this you can tell it to not to: cat file | xargs --null echo -ne Commented Sep 3, 2012 at 15:58

3 Answers 3

15

Why not:

while read -r line; do echo -e $line; done < at.txt
1
  • 1
    Leading whitespaces are missing in the output. I solved this by adding "IFS=" and enclosing $line in double quotes: while IFS= read -r line; do echo -e "$line"; done <at.txt
    – Daniel
    Commented May 1, 2021 at 9:08
14

You can simply:

echo -e $(cat at.txt)
1
  • 3
    Does not respect line breaks. Commented Feb 11, 2022 at 3:37
3

The built-in echo command interprets the common backslash escapes. But in a file you have to interpret, or convert it in a similar way. The sed program can do this.

sed -e 's/\\r/\r/' < at.txt

But I learned somethere here, also. The external echo command behaves differently from the internal one.

/bin/echo "\r"

Has different output than

echo "\r"

But basically you need a filter to convert the litteral \r string to a single byte 0x0D.

2
  • That's simply not correct … try echo "\r" vs. echo -e "\r". If it was the shell, both commands would output the same string.
    – knittl
    Commented Aug 29, 2012 at 10:26
  • The external echo behaves differently. And echo of sh behaves differently than echo of bash too
    – knittl
    Commented Aug 29, 2012 at 20:40

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