开发者

sed script to print the first three words in each line

开发者 https://www.devze.com 2023-02-10 17:04 出处:网络
I wonder how can I do the following thing with sed: I need to keep only the first three words in each line.

I wonder how can I do the following thing with sed: I need to keep only the first three words in each line. For example, the following text:

the quick brown fox jumps over the lazy bear
the bl开发者_运维百科ue lion is hungry

will be transformed in:

the quick brown
the blue lion


In awk you can say:

{print $1, $2, $3}


You can use cut like this:

cut -d' ' -f1-3


I would suggest awk in this situation:

awk '{print $1,$2,$3}' ./infile


% (echo "A B C D E F G H";echo "a b c d e f g h") | sed -E 's/([^\s].){3}//'

I put the "-E" in there for OS X compatibility. Other Unix systems may or may not need it.

edit: damnitall - brainfart. use this:

% sed -E 's/(([^ ]+ ){3}).*/\1/' <<END
the quick brown fox jumps over the lazy bear
the blue lion is hungry
END

the quick brown 
the blue lion 


Just using the shell

while read -r a b c d
do
  echo $a $b $c
done < file

Ruby(1.9)+

ruby -ane 'print "#{$F[0]} #{$F[1]} #{$F[2]}\n"' file


If you need a sed script, you can try:

echo "the quick brown fox jumps over the lazy bear" | sed 's/^\([a-zA-Z]\+\ [a-zA-Z]\+\ [a-zA-Z]\+\).*/\1/'

But I think it would be easier using cut:

echo "the quick brown fox jumps over the lazy bear" | cut -d' ' -f1,2,3


Here's an ugly one with sed:

$ echo the quick brown fox jumps over the lazy bear | sed 's|^\(\([^[:space:]]\+[[:space:]]\+\)\{2\}[^[:space:]]\+\).*|\1|'
the quick brown


If Perl is an option:

perl -lane 'print "$F[0] $F[1] $F[2]"' file
or
perl -lane 'print join " ", @F[0..2]' file

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号