Search code examples
sedword-count

How to insert total number of lines in a new line before the first line command?


I have thousands of .xyz files which are chemical coordinates like this one (for instance):

  Fe        0.000000000     0.000000000     0.000000000
   C        2.112450000     0.000000000     0.000000000
   C        0.039817193     1.817419422     0.000000000

I searched a lot for a simple command, like sed or head and tail, to write the counted number of lines on top of the file (with making a newline \n and with two spaces before the total number) but couldn't be successful. I would really appreciate any help given. The output mst be like this:

  3
Fe       0.000000000     0.000000000     0.000000000
C        2.112450000     0.000000000     0.000000000
C        0.039817193     1.817419422     0.000000000

Solution

  • You can do it as a composite command:

    (wc -l < fileA && cat fileA) > outputA
    

    Note that I used < there to make sure wc does not print the filename on the first line. On Mac OS at least, it does if you don't use redirection like that.


    Edit: If you need to apply the same to many files:

    mkdir output
    ls *.xyz | while read filename; do
        (wc -l < $filename && cat $filename) > output/$filename
    done
    

    Just for fun, here's a command that you should not use, but works in some cases:

    tee xxx < fileA | wc -l > xxx # don't do this