简体   繁体   中英

How to replace a file's content with a string containing new line characters?

When I read "line1\\nline2\\nline3" into a string, like this:

read string

line1\nline2\nline3

Then echo the string and direct the output to a file:

echo $string > text.txt

The txt file now contains:

line1nline2nline3

How could I make it so that the file contains:

line1
line2
line2

?

Thanks.

The problem here is that \\n does not mean line feed. It's just unnecessarily escaping the value of n .

To do what you want, you should.

  1. Read a string in a way that preserves backslashes
  2. Expand any escape sequences and write the string out

You can do 1. with read -r and 2. with echo -e :

read -r string
echo -e "$string"

只需将$string放在双引号中:

echo "$string" > text.txt

You need add double-quotes.

Example:

$ example=line1\nline2
$ echo $example
line1nline2

With double-quotes:

$ example="line1\nline2"
$ echo $example
line1
line2

Saving:

$ echo $example >> example.txt
$ cat example.txt
line1
line2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM