简体   繁体   中英

How to print "\n" character using bash?

I have a .csv file where some strings have some special characters like "\\n" (new line).

I'm using this script to extract the data from column 1 and 3:

while IFS=";" read f1 f2 f3 f4
do
        echo "\"$f1\" = \"$f3\";"
done < file.csv >file.txt

The main problem is that in some $f3 I have the \\n special character and I need to print it.

At the moment, this script is omitting this character.

eg If I have

\\nXPTO

it will print

XPTO

and I would expect that would print

\\nXPTO

Thanks

Use read -r to prevent read from interpreting escape sequences:

while IFS=";" read -r f1 f2 f3 f4
do
    echo "\"$f1\" = \"$f3\";"
done < file.csv >file.txt

Side Note: While it can be done with bash as I showed above, I agree with Karafka that awk is ideal for that kind of problems and performs very well. Better than bash itself, having that the input file has a significant size.

awk to the rescue!

$ echo "a;b;\nXPTO;d" | awk -F';' '{print $1 "=" $3}'

a=\nXPTO

or with file in/out

$ awk ... input_file > output_file

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