How to append the word count at the end of 10 digi

2019-08-12 12:27发布

问题:

I need to display the line count of the file at the end of the file as a trailer. I have 0000000000 (10 0's) , so if the line count is 2 then the string should be 0000000002, if the number of lines in the file are 120 then string should be 0000000120. I need to display this string at the end of the file as a trailer. Please help how this can be done in unix.

回答1:

you can try awk

awk '{print}END{printf("%010i\n", NR)}' file



回答2:

You can try:

printf "%010d" $(wc -l < file.txt) >> file.txt


回答3:

A simple sed onliner can do the task.

sed "$ s/$/\n0000000000$(wc -l < input)/" input

Test

$ cat test

hello
world
how
are
you

$  sed "$ s/$/\n0000000000$(wc -l < test)/" test

hello
world
how
are
you
00000000005

What it does??

  • $ matches the last line in the file

  • s/$/\n0000000000$(wc -l < input)/" subtitute, s the end of line, $ in the last line with 0000000000$(wc -l < input)

Note

You can use -i option in sed to edit the file inplace so that the change is made in the original file

$ sed -i "$ s/$/\n0000000000$(wc -l < test)/" test
$ cat test
hello
world
how
are
you
00000000005


标签: shell unix awk sed