416

これ

STR="Hello\nWorld"
echo $STR

出力として生成する

Hello\nWorld

それ以外の

Hello
World

文字列に改行を含めるにはどうすればよいですか?

注:この質問はechoに関するものではありません。 は認識していますが、文字列 (改行を含む) を引数として、 を改行として解釈する同様のオプションを持たない他のecho -eコマンドに渡すことができるソリューションを探しています。\n

4

13 に答える 13

441

Bash を使用している場合、解決策は を使用することです。$'string'次に例を示します。

$ STR=$'Hello\nWorld'
$ echo "$STR" # quotes are required here!
Hello
World

他のほとんどのシェルを使用している場合は、文字列に改行をそのまま挿入するだけです。

$ STR='Hello
> World'

バッシュはかなりいいです。文字列だけ\nではありません$''。以下は、Bash のマニュアル ページからの抜粋です。

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.
于 2010-07-05T22:43:03.403 に答える
194

Echo は非常に 90 年代であり、危険に満ちているため、使用すると 4GB 以上のコア ダンプが発生するはずです。真剣に言えば、echo の問題は、Unix 標準化プロセスが最終的にprintfユーティリティを発明し、すべての問題を排除した理由でした。

したがって、文字列内の改行を取得するには、次の 2 つの方法があります。

# 1) Literal newline in an assignment.
FOO="hello
world"
# 2) Command substitution.
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"

そこには!SYSV 対 BSD エコーの狂気はありません。すべてがきちんと印刷され、完全に移植可能な C エスケープ シーケンスのサポートが得られます。誰もprintfが、すべての出力ニーズに今すぐ使用し、決して振り返らないでください。

于 2012-05-16T12:06:03.393 に答える
67

他の回答に基づいて私がしたことは

NEWLINE=$'\n'
my_var="__between eggs and bacon__"
echo "spam${NEWLINE}eggs${my_var}bacon${NEWLINE}knight"

# which outputs:
spam
eggs__between eggs and bacon__bacon
knight
于 2012-12-01T11:26:47.543 に答える
31

問題はシェルではありません。問題は、実際にはechoコマンド自体にあり、変数補間を二重引用符で囲んでいないことです。使用してみることができますがecho -e、すべてのプラットフォームでサポートされているわけではありません。その理由の 1 つは、printf移植性のために現在推奨されています。

また、改行をシェルスクリプトに直接挿入してみてください(スクリプトがあなたが書いているものである場合)ので、次のようになります...

#!/bin/sh
echo "Hello
World"
#EOF

または同等に

#!/bin/sh
string="Hello
World"
echo "$string"  # note double quotes!
于 2010-06-09T13:19:29.277 に答える
4

私はbashの専門家ではありませんが、これはうまくいきました:

STR1="Hello"
STR2="World"
NEWSTR=$(cat << EOF
$STR1

$STR2
EOF
)
echo "$NEWSTR"

これにより、テキストの書式設定が簡単になりました。

于 2016-08-14T10:57:43.700 に答える