用换行符替换第一次出现的 MORE than one space

Replace the first occurrence of MORE than one space with newline

我正在尝试用换行符替换第一个有多个 space 的地方。

例如:

123 yes      foo bar       #

会变成:

123 yes
foo bar       #

我试过了

sed 's/^\s+/\n/' old > new

运气不好。我也对 linux 中允许我执行此操作的任何其他程序开放,例如 awk、perl 或 bash。

您正试图将行首与 ^ 相匹配。去掉它。并且您需要转义 + 字符。试试这个:

 sed 's/\s\s\+/\n/' old > new
 sed -r 's/\s\s+/\n/' old > new   # less escaping with extended regex syntax

您还可以使用 \{min,max\} 来定义更具体的重复。

 sed 's/\s\{2,\}/\n/' old > new
 sed -r 's/\s{2,}/\n/' old > new  # less escaping with extended regex syntax

您可以为此使用 awk

awk '{sub(/  +/,RS)}1' file
123 yes
foo bar       #

或者这样:

awk '{sub(/\s\s+/,RS)}1'

或者这样:

awk '{sub(/[[:space:]][[:space:]]+/,RS)}1'