0

I am trying to insert a line at the beginning of a file named text.txt that tells how many lines were in the text. Like:

35764
43587
12905
13944

After using the command, it should redirect the file into a textwc.txt, as

4

35764
43587
12905
13944

I tried to define a variable as a wc -l and tried to recall it into a awk, but i haven't achieve anything. Any ideas?

Inian
  • 80,270
  • 14
  • 142
  • 161

2 Answers2

2

1st solution: Could you please try following in awk.

awk -v lines="$(wc -l < Input_file)" 'FNR==1{print lines} 1' Input_file


2nd solution: With 2 times reading Input_file try following.

awk 'FNR==NR{count++;next} FNR==1{print count} 1' Input_file Input_file


3rd solution: Using tac + awk solution.

tac Input_file | awk '1;END{print FNR}' | tac


4th solution: In case your Input_file is NOT huge then try following.

awk '{val=(val?val ORS:"")$0}  END{print FNR ORS val}' Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

You can like this:

sed "1i $(wc -l < text.txt)" text.txt

Output:

4
35764
43587
12905
13944

Count number of line then insert to the first line using sed In case you want a empty line after #count, edit the inserted text

sed "1i $(wc -l < text.txt)\n" text.txt