Add file's date at beginning of every line in file

How would I do that?

/Rutger

$ ruby -ne 'BEGIN{s=File.mtime("file").to_s.gsub(/\s+/,"")};print "#{s} #{$_}" ' file
1 Like

Unfortunately I'm not having access to Ruby. I was more thinking of a solution that uses sed, awk, cat, or grep.

/Rutger

something along the lines of

 sed -e s/^/"`date` "/g FILE

Note: You will need the -i parameter for sed to change the file in place. The code above is non disruptive and non destructive to the original file.

1 Like

FYI, on OSX:

apple:~ neo$ vi aaa
apple:~ neo$ ruby -ne 'BEGIN{s=File.mtime("file").to_s.gsub(/\s+/,"")};print "#{s} #{$_}" ' aaa
-e:1:in `mtime': No such file or directory - file (Errno::ENOENT)
        from -e:1

I worked it out myself. I actually needed to do this operation on a couple of hundred files. The quick-and-dirty script looks like this:

#!/bin/bash
for i in *
do
awk -v string1=`ls $i |cut -c -14` '{ print string1";" $0 }' $i>> merged
done

FYI: the first 14 characters of the filename contained the date and time the file was created so I used that as the source for getting the file's date. The ";" character is the delimiter.

Rutger

I presume "aaa" is an empty file? FYI, on Linux and using 1.9.1,

$ wc -l < aaa
0
$ ruby -ne 'BEGIN{s=File.mtime("file").to_s.gsub(/\s+/,"")};print "#{s} #{$_}" ' aaa

It doesn't spew any errors. Thanks for this info on OSX