當我讀到「行1 \ nline2 \ nline3」成一個字符串,像這樣:如何用包含新行字符的字符串替換文件的內容?
read string
line1\nline2\nline3
然後呼應串並直接輸出到一個文件:
echo $string > text.txt
TXT文件現在包含:
line1nline2nline3
我怎麼可能讓這個文件包含:
line1
line2
line2
?
謝謝。
當我讀到「行1 \ nline2 \ nline3」成一個字符串,像這樣:如何用包含新行字符的字符串替換文件的內容?
read string
line1\nline2\nline3
然後呼應串並直接輸出到一個文件:
echo $string > text.txt
TXT文件現在包含:
line1nline2nline3
我怎麼可能讓這個文件包含:
line1
line2
line2
?
謝謝。
的這裏的問題是,\n
並不意味着換行。這只是不必要地逃避n
的價值。
要做你想做的,你應該做的。
你可以做1. read -r
和2. echo -e
方式的字符串:
read -r string
echo -e "$string"
只要把$string
在雙引號:
echo "$string" > text.txt
您需要添加雙引號。
例子:
$ example=line1\nline2
$ echo $example
line1nline2
用雙引號:
$ example="line1\nline2"
$ echo $example
line1
line2
保存:
$ echo $example >> example.txt
$ cat example.txt
line1
line2
+1爲正確的答案。對於OP,請閱讀[BashFAQ/001](http://mywiki.wooledge.org/BashFAQ/001)瞭解更多詳情。 –