如果您的输入已经在(bash)shell变量中,请说$varWithNewlines:
echo "${varWithNewlines//$'\n'/\n}"
Run Code Online (Sandbox Code Playgroud)
只需使用bash 参数扩展就可以$'\n'用文字替换所有newline()实例'\n'.
如果您的输入来自文件,请使用awk:
awk -v ORS='\\n' 1
Run Code Online (Sandbox Code Playgroud)
在行动中,通过示例输入:
# 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
Run Code Online (Sandbox Code Playgroud)
awk 逐行读取输入ORS- 输出记录分隔符到文字'\n'(使用附加进行转义\以便awk不将其解释为转义序列),输入行与该分隔符一起输出1只是简写{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}"
Run Code Online (Sandbox Code Playgroud)
相比之下,如果您希望根据输入是否以换行结束来存在终止文字,则需'\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
Run Code Online (Sandbox Code Playgroud)