Ubuntu – How to find a time stamp on a file and then echo it into the contents of the file as the first line

bashcommand linesed

I have the following command that I'm trying to tweak:

 stat -c %y test.txt | sed 's/^\([0-9\-]*\)/\1/'

This returns the following information:

 2016-08-03 14:52:24.000000000

I need to tweak this so that it excludes the ".000000000". I've tried a few different options but can't seem to get it right. Ultimately, I need to take the time stamp that I extract from the above command, and echo it as the first line into the file.

I have this command as an example that seems to correctly add a new line to the top of the file:

   sed -i '1s/^/this should be a date\n/' test.txt

How do I combine the two commands?

Best Answer

sed -i "1i$(stat -c %y test.txt | sed -r 's/\.[0-9]+ / /')" test.txt
Related Question