[英]Convert multiline string in a variable in bash to a single-line string with newlines escaped
I am looking for a way to convert a multiline string in a variable in bash to a single-line string that has each \n
character escaped as the \n
literal.我正在寻找一种将 bash 中的变量中的多行字符串转换为单行字符串的方法,该字符串将每个\n
字符转义为\n
文字。
For example:例如:
str="
Hello
World
"
I need this to become Hello\nWorld
.我需要这个成为Hello\nWorld
。 I looked through the questions on SO and Unix StackExchange but I haven't been able to find a command yet that achieves what I need.我查看了关于 SO 和 Unix StackExchange 的问题,但我还没有找到满足我需要的命令。
Bash has two built-in ways to quote values suitable for re-ingestion. Bash 有两种内置方式来引用适合重新摄取的值。 These will handle not only newlines but also tabs, quotes, and backslashes:这些不仅可以处理换行符,还可以处理制表符、引号和反斜杠:
❯ echo "${str@Q}"
$'\nHello\nWorld\n'
❯ printf '%q\n' "$str"
$'\nHello\nWorld\n'
Alternatively, if you simply want to replace newlines and nothing else you can use ${var//search/replace}
syntax to do replacements:或者,如果您只想替换换行符而没有其他内容,则可以使用${var//search/replace}
语法进行替换:
❯ echo "${str//$'\n'/\\n}"
\nHello\nWorld\n
Try:尝试:
sed -zn 's/\n/\\n/p' <<< "$str"
Use -z to consume the variable as one line and substitute new lines for literal newlines.使用 -z 将变量作为一行使用,并用新行替换文字换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.