繁体   English   中英

如何在 bash 中将换行符打印为 \\n?

[英]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'结尾即使您的输入没有以换行符结尾
这是因为awkORS终止每个输出行,无论输入行是否以换行符(在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.

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