亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在sh中的字符串中添加換行符?

如何在sh中的字符串中添加換行符?

慕尼黑5688855 2019-08-30 14:08:51
這個STR="Hello\nWorld"echo $STR產生輸出Hello\nWorld代替HelloWorld如何在字符串中添加換行符?注意:這個問題不是關于回聲。 我知道echo -e,但我正在尋找一種解決方案,允許將一個字符串(包括換行符)作為參數傳遞給其他命令,這些命令沒有類似的選項來解釋\n為換行符。
查看完整描述

3 回答

?
達令說

TA貢獻1821條經驗 獲得超6個贊

解決方案是使用$'string',例如:


$ STR=$'Hello\nWorld'

$ echo "$STR"

Hello

World

以下是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.


查看完整回答
反對 回復 2019-08-30
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

Echo是九十年代,充滿了危險,它的使用應該導致核心轉儲不低于4GB。說真的,echo的問題是Unix標準化過程最終發明printf實用程序的原因,消除了所有問題。


所以要在字符串中獲取換行符:


FOO="hello

world"

BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted

printf '<%s>\n' "$FOO"

printf '<%s>\n' "$BAR"

那里!沒有SYSV和BSD回聲瘋狂,一切都得到了整齊的打印和完全便攜式支持C轉義序列。大家請printf現在使用,永遠不要回頭。


查看完整回答
反對 回復 2019-08-30
?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

我根據其他答案做了什么


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


查看完整回答
反對 回復 2019-08-30
  • 3 回答
  • 0 關注
  • 1106 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號