简体   繁体   English

如何使用bash打印“\\n”字符?

[英]How to print "\n" character using bash?

I have a .csv file where some strings have some special characters like "\\n" (new line).我有一个 .csv 文件,其中一些字符串有一些特殊字符,如“\\n”(新行)。

I'm using this script to extract the data from column 1 and 3:我正在使用此脚本从第 1 列和第 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.主要问题是在某些$f3 中我有\\n特殊字符,我需要打印它。

At the moment, this script is omitting this character.目前,这个脚本省略了这个角色。

eg If I have例如,如果我有

\\nXPTO \\nXPTO

it will print它会打印

XPTO XPTO

and I would expect that would print我希望这会打印

\\nXPTO \\nXPTO

Thanks谢谢

Use read -r to prevent read from interpreting escape sequences:使用read -r防止read解释转义序列:

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.旁注:虽然它可以像我上面展示的那样用bash完成,但我同意Karafka 的观点,即awk是解决这类问题的理想选择,并且性能非常好。 Better than bash itself, having that the input file has a significant size.比 bash 本身更好,因为输入文件的大小很大。

awk to the rescue! awk来救援!

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

a=\nXPTO

or with file in/out或文件输入/输出

$ awk ... input_file > output_file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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