Reputation: 25
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
Upvotes: 0
Views: 140
Reputation: 15461
Try this:
sed '1i \
'$(wc -l < file.xyz) file.xyz
To process multiple files with find
and edit the files in place using the -i
flag:
find . -name '*.xyz' -exec sh -c 'sed -i "1s/.*/$(wc -l < {})\n&/" {}' \;
NB: as the files will be edited in place with this command, you may want to first check the output. To do so, remove the -i
flag after sed
. If the command meets your needs, then add the -i
flag again.
Upvotes: 1
Reputation: 249153
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
Upvotes: 1