Estimate number of lines in a file and insert that value as first line

99 Views Asked by At

I have many files for which I have to estimate the number of lines in each file and add that value as first line. To estimate that, I used something like this:

          wc -l 000600.txt | awk '{ print $1 }'

However, no success on how to do it for all files and then to add the value corresponding to each file as first line.

An example: a.txt b.txt c.txt

 >>print a
   15

 >> print b
   22

 >>print c
   56

Then 15, 22 and 56 should be added respectively to: a.txt b.txt and c.txt

I appreciate the help.

4

There are 4 best solutions below

0
On BEST ANSWER

This way you can add the line number as the first line for all *.txt files in current directory. Also using that group command here would be faster than inplace editing commands, in case of large files. Do not modify spaces or semicolons into the grouping.

for f in *.txt; do
    { wc -l < "$f"; cat "$f"; } > "${f}.tmp" && mv "${f}.tmp" "$f"
done
0
On

This might work for you (GNU sed):

sed -i '1h;1!H;$!d;=;x' file1 file2 file3 etc ...

Store each file in memory and insert the last lines line number as the file size.

Alternative:

sed -i ':a;$!{N;ba};=' file?
3
On

You can add a pattern for example (LINENUM) in first line of file and then use the following script.

 wc -l a.txt  | awk 'BEGIN {FS =" ";} { print $1;}' | xargs -I {} sed -i 's/LINENUM/LINENUM:{}/' a.txt

or just use from this script:

wc -l a.txt  | awk 'BEGIN {FS =" ";} { print $1;}' | xargs -I {} sed -i '1s/^/LINENUM:{}\n/' a.txt
1
On

For iterate over the all file you can add use from this script.

 for f in `ls *` ; do if [ -f $f ];  then wc -l $f  | awk 'BEGIN {FS =" ";} { print $1;}' | xargs -I {} sed -i '1s/^/LINENUM:{}\n/' $f ; fi;  done