如何从 Bash 中的字符串中删除换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19345872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:19:07  来源:igfitidea点击:

How to remove a newline from a string in Bash

bashvariables

提问by Matt Leyland

I have the following variable.

我有以下变量。

echo "|$COMMAND|"

which returns

返回

|
REBOOT|

How can I remove that first newline?

如何删除第一个换行符?

回答by F. Hauri

Under bash, there are some bashisms:

bash 下,有一些 bashisms:

The trcommand could be replaced by //bashism:

tr命令可以替换为//bashism

COMMAND=$'\nREBOOT\r   \n'
echo "|${COMMAND}|"
|
   OOT
|

echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT   |

echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|

See Parameter Expansionand QUOTINGin bash's man page:

请参阅bash 手册页中的参数扩展引用

man -Pless\ +/\/pattern bash
man -Pless\ +/\\'string\\' bash

man -Pless\ +/^\\ *Parameter\\ Exp bash
man -Pless\ +/^\\ *QUOTING bash

Further...

更远...

As asked by @AlexJordan, this will suppress allspecified characters. So what if $COMMANDdo contain spaces...

正如@AlexJordan 所问,这将抑制所有指定的字符。那么如果$COMMAND确实包含空格怎么办...

COMMAND=$'         \n        RE BOOT      \r           \n'
echo "|$COMMAND|"
|
           BOOT      
|

CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
|                 RE BOOT                 |

shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}

CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
|                 RE BOOT|

CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|

Shortly:

不久:

COMMAND=$'         \n        RE BOOT      \r           \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|

Note: bashhave extgloboption to be enabled (shopt -s extglob) in order to use *(...)syntax.

注意:bash可以extglob选择启用 ( shopt -s extglob) 以使用*(...)语法。

回答by Robin Green

echo "|$COMMAND|"|tr '\n' ' '

will replace the newline (in POSIX/Unix it's not a carriage return) with a space.

将用空格替换换行符(在 POSIX/Unix 中它不是回车符)。

To be honest I would think about switching away from bash to something more sane though. Or avoiding generating this malformed data in the first place.

老实说,我会考虑从 bash 转向更理智的东西。或者首先避免生成这种格式错误的数据。

Hmmm, this seems like it could be a horrible security hole as well, depending on where the data is coming from.

嗯,这似乎也可能是一个可怕的安全漏洞,具体取决于数据的来源。

回答by Maxime Chéramy

Clean your variable by removing all the carriage returns:

通过删除所有回车来清理变量:

COMMAND=$(echo $COMMAND|tr -d '\n')

回答by wjordan

Using bash:

使用bash

echo "|${COMMAND/$'\n'}|"

(Note that the control character in this question is a 'newline' (\n), not a carriage return (\r); the latter would have output REBOOT|on a single line.)

(请注意,此问题中的控制字符是“换行符” ( \n),而不是回车符 ( \r);后者将REBOOT|在单行上输出。)

Explanation

解释

Uses the Bash Shell Parameter Expansion${parameter/pattern/string}:

使用 Bash Shell 参数扩展${parameter/pattern/string}

The patternis expanded to produce a pattern just as in filename expansion. Parameteris expanded and the longest match of patternagainst its value is replaced with string. [...] If stringis null, matches of patternare deleted and the /following patternmay be omitted.

图案被膨胀,以产生一个模式,就像在文件名扩展。参数被扩展,模式与其值的最长匹配被替换为string。[...] 如果string为空,则删除模式的匹配项,并且可以省略/后面的模式

Also uses the $''ANSI-C quotingconstruct to specify a newline as $'\n'. Using a newline directly would work as well, though less pretty:

还使用$''ANSI-C 引用构造将换行符指定为$'\n'. 直接使用换行符也可以,虽然不那么漂亮:

echo "|${COMMAND/
}|"

Full example

完整示例

#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|

Or, using newlines:

或者,使用换行符:

#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|

回答by Prachi

What worked for me was echo $testVar | tr "\n" " "

对我有用的是 echo $testVar | tr "\n" " "

Where testVar contained my variable/script-output

testVar 包含我的变量/脚本输出的地方

回答by gaoithe

Adding answer to show example of stripping multiple characters including \r using tr and using sed. And illustrating using hexdump.

添加答案以显示使用 tr 和使用 sed 剥离多个字符的示例,包括 \r。并说明使用 hexdump。

In my case I had found that a command ending with awk print of the last item |awk '{print $2}'in the line included a carriage-return \r as well as quotes.

就我而言,我发现|awk '{print $2}'以该行最后一项的 awk 打印结尾的命令包括回车 \r 和引号。

I used sed 's/["\n\r]//g'to strip both the carriage-return and quotes.

我曾经sed 's/["\n\r]//g'去掉回车符和引号。

I could also have used tr -d '"\r\n'.

我也可以使用tr -d '"\r\n'.

Interesting to note sed -zis needed if one wishes to remove \n line-feed chars.

sed -z如果希望删除 \n 换行符,则需要注意。

$ COMMAND=$'\n"REBOOT"\r   \n'

$ echo "$COMMAND" |hexdump -C
00000000  0a 22 52 45 42 4f 4f 54  22 0d 20 20 20 0a 0a     |."REBOOT".   ..|

$ echo "$COMMAND" |tr -d '"\r\n' |hexdump -C
00000000  52 45 42 4f 4f 54 20 20  20                       |REBOOT   |

$ echo "$COMMAND" |sed 's/["\n\r]//g' |hexdump -C
00000000  0a 52 45 42 4f 4f 54 20  20 20 0a 0a              |.REBOOT   ..|

$ echo "$COMMAND" |sed -z 's/["\n\r]//g' |hexdump -C
00000000  52 45 42 4f 4f 54 20 20  20                       |REBOOT   |

And this is relevant: What are carriage return, linefeed, and form feed?

这是相关的: 什么是回车、换行和换页?

  • CR == \r == 0x0d
  • LF == \n == 0x0a
  • CR == \r == 0x0d
  • LF == \n == 0x0a

回答by Paulo

You can simply use echo -n "|$COMMAND|".

您可以简单地使用echo -n "|$COMMAND|".

回答by zeroimpl

If you are using bash with the extglob option enabled, you can remove just the trailing whitespace via:

如果您在启用 extglob 选项的情况下使用 bash,您可以通过以下方式仅删除尾随空格:

shopt -s extglob
COMMAND=$'\nRE BOOT\r   \n'
echo "|${COMMAND%%*([$'\t\r\n '])}|"

This outputs:

这输出:

|
RE BOOT|

Or replace %% with ## to replace just the leading whitespace.

或者用 ## 替换 %% 以仅替换前导空格。