tags:

views:

35

answers:

2

hi all

I used the following awk in order to count all words that appears in field 4

  awk '{print $4}'  file | awk '{print NF}' | grep -c 1

How we can to the same in sed?

Example of file:

 1 2 3 4
 1 2 
 1 2 3 4 5
 1 2
 1 2 3
 1 2 3 4

From file sed should return the results 3 (three words on field 4)

yael

+1  A: 

First of all, your awk is quite inefficient. Try this:

awk '$4{c++}END{print c}' file

Why do you want it in sed, BTW? This is what awk does well. If you really want it in sed, I guess something like this:

sed '/^\s*\S*\s*\S*\s*\S*\s*$/d' file | wc -l

awk explanation: In every line where fourth field is non-null, increment c. At the end, print c.

sed explanation: delete each line which matches the regexp. Then with wc count the lines of the sed output. The regexp basically says there can be maximum of two whitespace groups in the line, not counting initial and final ones, which then means there can be at most 3 fields in the line.

Amadan
A: 

cut can also be used:

cut -f 5 -d' ' file | wc -w

Select the 5. column (the first one is empty due to the leading blank). The delimiter is a blank.

fgm