我在一行中有这个:
We were born in the earth beyond the land
我希望它在 3 个单词行中,如下所示:
We were born
in the earth
beyond the land
$ xargs -n3 < file
We were born
in the earth
beyond the land
$ egrep -o '\S+\s+\S+\s+\S+' file
We were born
in the earth
beyond the land
使用 GNU sed:
sed 's/\(\w\w*\W*\w\w*\W*\w\w*\W*\)/\1\n/g' input
和短版:
sed 's/\(\(\w\w*\W*\)\{3\}\)/\1\n/g' input
使用awk
:
awk '{
for ( i = 1; i <= NF; i++ ) {
printf "%s%c", $i, (i % 3 == 0) ? ORS : OFS
}
}' infile
它产生:
We were born
in the earth
beyond the land
这是一个 sed 解决方案:
sed -e 's/\s/\n/3;s/\s/\n/6;s/\s/\n/9'
它用换行符替换第三、第六和第九个空格。
这个将处理更长的行,即使它们不是三个单词的倍数:
sed -e 's/\(\(\S\{1,\}\s*\)\{3\}\)/\1\n/g'
任何有 awk 和 sed 的系统几乎肯定也会有 Perl:
cat myfile.txt | perl -lane 'while(($a,$b,$c) = splice(@F,0,3)){print "$a $b $c"}'