Insert word count of the file as a number

September 16, 2010 at 03:21:00
Specs: Linux, intel
Hi.,

I would like to know how shall I insert the word count of a file into the same file as its first line (using one liners like SED).
I hope you would get me the solution.

arunkumar.cr


See More: Insert word count of the file as a number

Report •

#1
September 16, 2010 at 05:23:07
sed is not the right tool if you are doing something beyond string manipulation. use awk instead.

gawk 'FNR==NR{wc+=NF;next}FNR==1&&FNR!=NR{$0=wc"\n"$0}1' file file

Next time, show a little more effort before asking for solution.!

GNU win32 packages | Gawk


Report •

#2
September 16, 2010 at 06:08:47
Thank you....! :-)

Report •

#3
September 22, 2010 at 09:37:49
Hi, Thanks for your previous reply.

I am requesting you to answer my second question, because I am not good at
GAWK. I would like to insert the line count into the first line of a file. How can
I achieve that?

I hope you would reply to my query.

Thanking you

Sincerely
arun


Report •

Related Solutions

#4
September 22, 2010 at 18:02:09
have you even tried running the gawk command? It inserts the line count at first line, isn't that what you wanted?

GNU win32 packages | Gawk


Report •

#5
September 22, 2010 at 23:21:36
Suppose I have the file new.dat with contents

dat1 dat2 dat3
some txt here
some txt here
some txt here

Then I want the file written as
4
dat1 dat2 dat3
some txt here
some txt here
some txt here

This is what I meant by adding the no: of lines at the first line of the file.


Report •

#6
September 23, 2010 at 03:10:48
you have not answered my question. Did you bother to run the command i gave ?

GNU win32 packages | Gawk


Report •

#7
September 23, 2010 at 03:31:01
Not exactly. Your command writes the no: of words on the first line and not the no: of lines. For ex., if I run your command for my earlier input, it reports the output as,
12
dat1 dat2 dat3
some txt here
some txt here
some txt here

Hope you have noticed that.


Report •

#8
September 23, 2010 at 04:00:41
dude, your first post says word count, not line count. Now if you want line count, use NR.
awk 'FNR==1{a=NR-1}NR>FNR&&FNR==1{print a}NR>FNR' file file

GNU win32 packages | Gawk


Report •

#9
September 23, 2010 at 06:07:18

That's it! Finally it works! Thank you..........!

Report •

Ask Question