[英]Sed Command substitution how do you treat spaces or multiple spaces as one?
I use this command to insert a line. 我使用此命令插入一行。 If there is a space in the pattern between two entries in the text or file it prints the content on the new line.
如果文本或文件中两个条目之间的模式中有空格,它将在新行上打印内容。 It works fine, however sometimes I encounter 2 spaces or 3 spaces instead of one that I'm looking for in the pattern so I get additional blank lines.
它工作正常,但是有时候我遇到2个空格或3个空格,而不是我在模式中寻找的1个空格,所以我得到了额外的空行。
sed "s/ /\n/g"
I want to print a new line only the sed finds something in the pattern. 我只想在sed模式中找到某些内容时打印新行。 How should I use the sed command to treat 1 space or double or triple spaces as one substitute?
我应该如何使用sed命令将1个空格或双倍或三倍空格视为一种替代?
You need a quantifier: 您需要一个量词:
sed "s/ */\n/g"
or 要么
sed 's/ \+/\n/g' # With GNU sed
or 要么
sed -r 's/ +/\n/g'
or 要么
sed 's/ \{1,\}/\n/g'
or 要么
sed -r 's/ {1,}/\n/g'
If using BSD sed, 如果使用BSD sed,
sed 's/ */\'$'\n''/g'
or 要么
sed -r 's/ +/\'$'\n''/g'
You could also use tr
: 您也可以使用
tr
:
tr -s ' ' '\n'
The -s
option squeezes repeats of a character in set1, ie the ' '
in this example. -s
选项压缩 set1中字符的重复,即本例中的' '
。
I would do something like... 我会做类似...
sed -e 's/\s\+/\n/g' [filename]
To find and replace one or more white space with a new line. 查找并用换行替换一个或多个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.