Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed script to print the first three words in each line

Tags:

scripting

sed

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 blue lion is hungry

will be transformed in:

the quick brown
the blue lion
like image 820
BearCode Avatar asked Feb 14 '11 23:02

BearCode


People also ask

How do I print the first word in a shell script?

To print a whole word, you want -f 1 , not -c 1 . And since the default field delimiter is TAB rather than SPACE, you need to use the -d option.

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

How do you sed multiple times?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.

How do you use sed to match word and perform find and replace?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


1 Answers

In awk you can say:

{print $1, $2, $3}
like image 166
lhf Avatar answered Sep 16 '22 12:09

lhf