shin
shin

Reputation: 32721

How to touch files with different names and different date created

I am trying to create files with different date created:

$ touch -t 20{11..15}01120000 file_{1..5}.txt
$ ls -al 
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 201201120000
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 201301120000
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 201401120000
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 201501120000
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 file_1.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 file_2.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 file_3.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 file_4.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 file_5.txt

As you can see all file's dates created are 2011 Jan 12 0.

How can I create files with a different year?

# this is what I want
-rw-r--r--   1 shinokada  staff     0 Jan 12  2011 file_1.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2012 file_2.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2013 file_3.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2014 file_4.txt
-rw-r--r--   1 shinokada  staff     0 Jan 12  2015 file_5.txt

What is the best way?

Upvotes: 3

Views: 1222

Answers (3)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70752

Shortly, but keeping filenumbers and years as separated variables

I think this is more readable, but...

Care about timezone!

filenum=1
for year in {2011..2015};do
    TZ=UTC touch -t ${year}12312345 file-$((filenum++))
  done

Then if you look about this, using a different timezone: (Note that created date was Dec 31, 23h45')

TZ=UTC-1 ls -ltr
-rw-r--r-- 1 user user      0 jan  1  2012 file-1
-rw-r--r-- 1 user user      0 jan  1  2013 file-2
-rw-r--r-- 1 user user      0 jan  1  2014 file-3
-rw-r--r-- 1 user user      0 jan  1  2015 file-4
-rw-r--r-- 1 user user      0 jan  1  2016 file-5

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following, I would go with following approach with a for loop. Where I am providing year, number of files which needed, output file's initial value and same time value for all output files so that we can manage it in for loop.

cat script.bash
year=2011
numberoffiles="10"
time="01120000"
outputfileInitials="file"
nameSequence="1"

for ((i = 1 ; i <= numberoffiles ; i++ ));
do
  touch -t $year$time "${outputfileInitials}_$nameSequence.txt"
  (( nameSequence =  nameSequence + 1 ))
  (( year = year + 1 ))
done

Upvotes: 0

anubhava
anubhava

Reputation: 784998

touch command allows you to enter one one timestamp using -t option.

A traditional for-loop would be better:

for i in {1..5}; do touch -t 201${i}01120000 file_$i.txt; done

Upvotes: 1

Related Questions