tags:

views:

55

answers:

3

This

STR="Hello\nWorld"
echo $STR

produces as output

Hello\nWorld

instead of

Hello
World

What should I do to have a newline in a string? I'm aware of echo -e, but I'm no sending the string to echo, the string will be used as an argument by another command that doesn't know how to interpret \n as a newline.

A: 

The problem isn't with the shell. The problem is actually with the echo command itself. You can try using echo -e but that isn't supported on all platforms. You can also try and insert the newline directly into your shell script (if a script is what you're writing) so it looks like...

#!/bin/sh
echo "Hello
World"
#EOF
Pace
+3  A: 

Solution:

I figured it out. Here is an excerpt from the Bash manual page:

   Words of the form $'string' are treated specially.  The word expands to
   string, with backslash-escaped characters replaced as specified by  the
   ANSI  C  standard.  Backslash escape sequences, if present, are decoded
   as follows:
          \a     alert (bell)
          \b     backspace
          \e
          \E     an escape character
          \f     form feed
          \n     new line
          \r     carriage return
          \t     horizontal tab
          \v     vertical tab
          \\     backslash
          \'     single quote
          \"     double quote
          \nnn   the eight-bit character whose value is  the  octal  value
                 nnn (one to three digits)
          \xHH   the  eight-bit  character  whose value is the hexadecimal
                 value HH (one or two hex digits)
          \cx    a control-x character

   The expanded result is single-quoted, as if the  dollar  sign  had  not
   been present.

   A double-quoted string preceded by a dollar sign ($"string") will cause
   the string to be translated according to the current  locale.   If  the
   current  locale  is  C  or  POSIX,  the dollar sign is ignored.  If the
   string is translated and replaced, the replacement is double-quoted.

Therefore:

$ STR=$'Hello\nWorld'
$ echo "$STR"
Hello
World

Old Answer:

I'm not sure what you can do in order to have escape characters actually reside inside of strings as-typed in your scripts, short of:

STR="$(echo -e 'Hello\nWorld')"

What you can try is this:

$ shopt -s xpg_echo
$ echo "Hello\nWorld"
Hello
World

Or

$ echo -e "Hello\nWorld"
Hello
World

The xpg_echo shell option "If set, the echo builtin expands backslash-escape sequences by default." (GNU Bash man page). Keep in mind that it doesn't actually insert a newline inside the string; it's what echo does with the \n that changes.

amphetamachine
A: 

Another solution, which should work even in crufty old implementations of sh:


$ eval STR="'$(printf 'Hello\nworld')'"
$ echo "$STR"
Hello
world

William Pursell