sed 用一个空格替换所有制表符和空格

Zul*_*kis 27 domain-name-system linux bash sed dig

我得到了一个如下所示的字符串:

test.de.          1547    IN      SOA     ns1.test.de. dnsmaster.test.de. 2012090701 900 1000 6000 600
Run Code Online (Sandbox Code Playgroud)

现在我想用一个空格替换记录之间的所有制表符/空格,以便我可以轻松地使用它 cut -d " "

我尝试了以下方法:

sed "s/[\t[:space:]]+/[:space:]/g"
Run Code Online (Sandbox Code Playgroud)

和各种变体,但无法正常工作。有任何想法吗?

Sta*_*ish 51

sed -e "s/[[:space:]]\+/ /g"

这是一个解释:

[   # start of character class

  [:space:]  # The POSIX character class for whitespace characters. It's
             # functionally identical to [ \t\r\n\v\f] which matches a space,
             # tab, carriage return, newline, vertical tab, or form feed. See
             # https://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes

]   # end of character class

\+  # one or more of the previous item (anything matched in the brackets).
Run Code Online (Sandbox Code Playgroud)

对于您的替换,您只想插入一个空格。[:space:]不会在那里工作,因为这是字符类的缩写,正则表达式引擎不知道该放什么字符。

+必须在正则表达式进行转义,因为使用sed的正则表达式引擎+是一个正常的字符,而\+对于“一个或多个”元字符。在Mastering Regular Expressions 的第 86 页上,Jeffrey Friedl 在脚注中提到 ed 和 grep 使用转义括号,因为“Ken Thompson 认为正则表达式将主要用于 C 代码,其中需要匹配原始括号比反向引用更常见.” 我假设他对加号也有同样的感觉,因此需要将其转义以将其用作元字符。很容易被这个绊倒。

在sed你需要逃跑+?|(,和)。或使用 -r 使用扩展正则表达式(然后它看起来像sed -r -e "s/[[:space:]]\+/ /g"sed -re "s/[[:space:]]\+/ /g"

  • [[:space:]] 等价于 '\s',所以较短的版本是 "s/\s\+/ /g" (3认同)
  • 当用于表示“一个或多个前一个字符或组”时,基本正则表达式在加号之前使用反斜杠,来源 https://developer.apple.com/library/mac/#documentation/opensource/conceptual/shellscripting /RegularExpressionsUnfettered/RegularExpressionsUnfettered.html。 (2认同)

Ben*_* W. 7

您可以使用-s(“挤压”)选项tr

$ tr -s '[:blank:]' <<< 'test.de.          1547    IN      SOA     ns1.test.de. dnsmaster.test.de. 2012090701 900 1000 6000 600'
test.de. 1547 IN SOA ns1.test.de. dnsmaster.test.de. 2012090701 900 1000 6000 600
Run Code Online (Sandbox Code Playgroud)

[:blank:]字符类既包括空格和制表符。