0

I want to count how many rows are in one file with defined length to show.

In normal case example:

file:

2423
546
74868

cat file|wc -l will show the result: 3.

But I want to defined length of the numbers for example to have 10 symbols and to show:

0000000003

if there are 100 lines to be:

0000000100
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Kalin Borisov
  • 1,091
  • 1
  • 12
  • 23
  • 1
    similar: http://stackoverflow.com/questions/26902438/how-to-append-the-word-count-at-the-end-of-10-digit-number-in-unix/26903103#26903103 – ghostdog74 Nov 14 '14 at 12:37

3 Answers3

4

I think that you want something like this:

printf '%010d' $(wc -l < file)

The format specifier %010d means print 10 digits, padded with leading 0s.

As a bonus, in using < to pass the contents of the file via standard input, I have saved you a "useless use of cat" :)

If I understand your comment correctly, you can do something like this:

printf 'Count: %010d' $(( $(wc -l < file) + 1 ))

Here I have added some additional text to the format specifier and used an arithmetic context $(( )) to add one to the value of the line count.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
4
perl -ne '}{ printf("%010d\n", $.)' file

Reference to counting lines in perl.

mpapec
  • 50,217
  • 8
  • 67
  • 127
1

With awk:

awk 'END{printf("%010d\n",NR)}' file
  • Note that this `awk` approach is way more slow than the `wc` option, I guess because `wc` is more optimized as it is *the* tool for this work. I just compared doing `seq 10000000 > a` and then counting with both methods. `wc` was 7 times faster! Of course, the time was almost negligible, just compared for fun. – fedorqui Nov 14 '14 at 13:14
  • @fedorqui did your timing include formatting the digits output by wc using printf or similar? I found the timings to be about 1:3 rather than 1:7 when I compared the awk solution to `printf "%010d\n" $(wc -l < a)`. As you would expect, of course, wc is faster since it's not trying to split lines into fields and populating builtin variables for each line. – Ed Morton Nov 14 '14 at 15:42
  • @EdMorton no, I just compared `wc -l real 0m0.052s user 0m0.039s sys 0m0.013s` and `awk --> real 0m0.373s user 0m0.366s sys 0m0.005s`. – fedorqui Nov 14 '14 at 16:31