sed匹配模式N次


14

我想将文件拆分为每个2个单词的块。

$cat tmp
word1 word2 word3 word4 word5 word6 word7
$sed -e 's/word. word. /&\n/g' tmp
word1 word2 
word3 word4 
word5 word6 
word7
$sed -e 's/word. \{2\}/&\n/g' tmp
word1 word2 word3 word4 word5 word6 word7

我希望最后一个命令给出与之前相同的结果。怎么了?

Answers:


17

抱歉,似乎我刚发布后就知道了。

它必须是

sed -e 's/\(word. \)\{2\}/&\n/g' tmp

显然,需要括号来使sed {2}在整个模式上word.而不是仅在前一个空格上应用条件。


3
或使用sed -E 's/(word. ){2}/&\n/g' tmp
Cyrus


1

对于匹配N次的一般情况:

$ perl -ple '$N=3;s/(\S+ ){$N}\K/\n/g' tmp
word1 word2 word3 
word4 word5 word6 
word7
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.