Sed script to print the first three words on each line

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

the quick brown fox jumps over the lazy bear the blue lion is hungry 

will be converted to:

 the quick brown the blue lion 
+7
source share
8 answers

You can use cut as follows:

 cut -d' ' -f1-3 
+13
source

In awk you can say:

 {print $1, $2, $3} 
+16
source

I would suggest awk in this situation:

 awk '{print $1,$2,$3}' ./infile 
+5
source
 % (echo "ABCDEFGH";echo "abcdefgh") | sed -E 's/([^\s].){3}//' 

I put "-E" 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 
+5
source

Just using a shell

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

Ruby (1.9) +

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

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 to use cut:

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

Here's ugly with sed :

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

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
source

All Articles