[英]How can I print a newline as \n in bash?
基本上我想实现类似于echo -e
的倒数。 我有一个存储命令输出的变量,但我想将换行符打印为 \\n。
这是我的解决方案:
sed 's/$/\\n/' | tr -d '\n'
如果您的输入已经在( bash
) shell 变量中,请说$varWithNewlines
:
echo "${varWithNewlines//$'\n'/\\n}"
只需使用bash
参数扩展将所有换行符 ( $'\\n'
) 实例替换为文字'\\n'
。
如果您的输入来自文件,请使用awk
:
awk -v ORS='\\n' 1
在行动中,使用示例输入:
# Sample input with actual newlines created with ANSI C quoting ($'...'),
# which turns `\n` literals into actual newlines.
varWithNewlines=$'line 1\nline 2\nline 3'
# Translate newlines to '\n' literals.
# Note the use of `printf %s` to avoid adding an additional newline.
# By contrast, a here-string - <<<"$varWithNewlines" _always appends a newline_.
printf %s "$varWithNewlines" | awk -v ORS='\\n' 1
awk
逐行读取输入ORS
-输出记录分隔符设置为文字'\\n'
(用额外的\\
转义,以便awk
不会将其解释为转义序列),输入行将使用该分隔符输出1
只是{print}
简写,即{print}
所有输入行,以ORS
终止。 注意:输出将始终以文字'\\n'
结尾,即使您的输入没有以换行符结尾。
这是因为awk
用ORS
终止每个输出行,无论输入行是否以换行符(在FS
指定的分隔符)结束。
以下是如何从输出中无条件地去除终止文字'\\n'
的方法。
# Translate newlines to '\n' literals and capture in variable.
varEncoded=$(printf %s "$varWithNewlines" | awk -v ORS='\\n' 1)
# Strip terminating '\n' literal from the variable value
# using bash parameter expansion.
echo "${varEncoded%\\n}"
相比之下,如果您想让终止文字'\\n'
取决于输入是否以换行符结尾,则需要做更多的工作。
# Translate newlines to '\n' literals and capture in variable.
varEncoded=$(printf %s "$varWithNewlines" | awk -v ORS='\\n' 1)
# If the input does not end with a newline, strip the terminating '\n' literal.
if [[ $varWithNewlines != *$'\n' ]]; then
# Strip terminating '\n' literal from the variable value
# using bash parameter expansion.
echo "${varEncoded%\\n}"
else
echo "$varEncoded"
fi
您可以使用printf "%q"
:
eol=$'\n'
printf "%q\n" "$eol"
$'\n'
Bash 解决方案
x=$'abcd\ne fg\nghi'
printf "%s\n" "$x"
abcd
e fg
ghi
y=$(IFS=$'\n'; set -f; printf '%s\\n' $x)
y=${y%??}
printf "%s\n" "$y"
abcd\ne fg\nghi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.