0

I have a text file:

10 20 30 40
50 60 60 80

By using

$ wc -l file.txt
2 file.txt

I get the count, but I want to add that result in my text file.

I want the result to be like this:

2
10 20 30 40
50 60 70 80

What should I do in order to prepend the result in the text file?

I have many of these files in one folder, and instead of providing a single text file at a time, I want to provide all the files at the same time.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
BHAV247
  • 69
  • 1
  • 11

3 Answers3

1

For one file, you can do this:

wc -l < file.txt | cat - file.txt > tmp && mv tmp file.txt

This uses cat to concatenate the result of wc -l < file.txt with the contents of file.txt. The result is written to a temporary file, then the original file is overwritten.

For many files (e.g. all files ending in .txt), you can use a loop:

for file in *.txt; do
    wc -l < "$file" | cat - "$file" > tmp && mv tmp "$file"
done
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

Try:

echo `wc -l myfile.txt` | cat - myfile.txt > tmp && mv tmp myfile.txt 
Dummy00001
  • 16,630
  • 5
  • 41
  • 63
nouseforname
  • 720
  • 1
  • 5
  • 17
0

Awk may be your friend :

awk 'BEGIN{RS="^$"}NR=FNR{printf "%d\n%s",gsub(/\n/,"\n"),$0}' file \
> temp && mv temp file
sjsam
  • 21,411
  • 5
  • 55
  • 102