script to insert no. of lines in a file to the start of the file
Hey all
I'm looking for a way to insert the number of lines in a file to the start of the aformentioned file. This should be simple but as I am not used to scripts in Linux, I am finding it tough going.
I can find the number of lines in a file easily enough via
filesize=$(awk 'END {print NR}' $1)
but as for inserting this into the first line, i'm failing to do so. I've tried some of the other approaches on these forums but none so far have been able to do so.
I've tried:
sed '1i\$filesize' $1
but sed i requires a string, not a variable so no go
I've also tried:
mv "$1" "${1}.bak" 2>/dev/null || touch "${1}.bak"
cat $filesize "${1}.bak" >"$1"
but again with no luck as cat seems to need an input stream
Would someone be able to illuminate me with a good way to do so?
Just to recap, i want to insert a line at the start of a given file that holds the number of lines the original file has.
ie the file:
a
b
c
d
e
should become:
5
a
b
c
d
e
Thanks in advance
|