How to capture last modified date of a file in avariable - linux

How to capture last modified date of a file in a variable.
Consider a directory '/home/abc/Desktop/swa` containing files:
abc1.txt
abc2.txt
abc3.txt
How to capture the last modified date for file abc2.txt in a variable?

Use stat like this:
mtime=$(stat -c "%y" abc2.txt)
echo $mtime
2014-03-04 09:15:31.000000000 +0000
Or, if you just want age in seconds since the Epoch for simple comparisons:
mtime=$(stat -c "%Y" abc2.txt)
echo $mtime
1393924531

Use stat(1) e.g.
modate=$(stat --format='%Y' abc1.txt)

Related

Changing File name Dynamically in linux bash

I want to change a filename "Domain_20181012230112.csv" to "Domain_12345_20181012230112.csv" where "Domain" and "12345" are constants while 20181012230112 is always gonna change but with fix length. In bash how can I do this
If all you want is to replace Domain_ with Domain_12345_, then just do
for file in Domain_*;
do
mv "$file" "${file/Domain_/Domain_12345_}"
done
You can make it even shorter if you know that there will only be one underscore:
...
mv "$file" "${file/_/_12345_}"
...
See string substitutions for more info.
You can use mv in a for loop, like this:
for file in Domain_??????????????.csv ; do ts=`echo ${file} | cut -c8-21`; mv ${file} Domain_12345_${ts}.csv; done
Given the one file of your example, this will essentially execute this command
mv Domain_20181012230112.csv Domain_12345_20181012230112.csv
You can simply use the date command to get the date and time information you want
date '+%Y-%m-%d %H:%M:%S'
# 2018-10-26 10:25:47
To then use the result within the filename, you can put it in `` to evaluate it inline, for example you can run
echo "Domain_12345_`date '+%Y-%m-%d %H:%M:%S'`"
# Domain_12345_2018-10-26 10:29:17
You can use the date's man page to figure out the option for milliseconds to add es well.
man date
There are different options like %m and %d for example that always have leading zeroes if necessary, so the file name length stays constant.
To then rename the file you can use the mv (move) command
mv "Domain_20181012230112.csv" "Domain_12345_`date '+%Y-%m-%d %H:%M:%S'`.csv"
Good luck with the rest of the exercise!

bash loop file echo to each file in the directory

I searched a while and tried it by myself but unable to get this sorted so far. My folder looks below, 4 files
1.txt, 2.txt, 3.txt, 4.txt, 5.txt, 6.txt
I want to print file modified time and echo the time stamp in it
#!/bin/bash
thedate= `ls | xargs stat -s | grep -o "st_mtime=[0-9]*" | sed "s/st_mtime=//g"` #get file modified time
files= $(ls | grep -Ev '(5.txt|6.txt)$') #exclud 5 and 6 text file
for i in $thedate; do
echo $i >> $files
done
I want to insert each timestamp to each file. but having "ambiguous redirect" error. am I doing it incorrectly? Thanks
In this case, files is a "list" of files, so you probably want to add another loop to handle them one by one.
Your description is slightly confusing but, if your intent is to append the last modification date of each file to that file, you can do something like:
for fspec in [1-4].txt ; do
stat -c %y ${fspec} >>${fspec}
done
Note I've used stat -c %y to get the modification time such as 2017-02-09 12:21:22.848349503 +0800 - I'm not sure what variant of stat you're using but mine doesn't have a -s option. You can still use your option, you just have to ensure it's done on each file in turn, probably something like (in the for loop above):
stat -s ${fspec} | grep -o "st_mtime=[0-9]*" | sed "s/st_mtime=//g" >>${fspec}
You can not redirect the output to several files as in > $files.
To process several files you need something like:
#!/bin/bash
for f in ./[0-4].txt ; do
# get file modified time (in seconds)
thedate="$(stat --printf='%Y\n' "$f")"
echo "$thedate" >> "$f"
done
If you want a human readable time format change %Y by %y:
thedate="$(stat --printf='%y\n' "$f")"

How can i format the output of stat expression in Linux Gnome Terminal?

I am really newbie in Linux(Fedora-20) and I am trying to learn basics
I have the following command
echo "`stat -c "The file "%n" was modified on ""%y" *Des*`"
This command returns me this output
The file Desktop was modified on 2014-11-01 18:23:29.410148517 +0000
I want to format it as this:
The file Desktop was modified on 2014-11-01 at 18:23
How can I do this?
You can't really do that with stat (unless you have a smart version of stat I'm not aware of).
With date
Very likely, your date is smart enough and handles the -r switch.
date -r Desktop +"The file Desktop was modified on %F at %R"
Because of your glob, you'll need a loop to handle all files that match *Des* (in Bash):
shopt -s nullglob
for file in *Des*; do
date -r "$file" +"The file ${file//%/%%} was modified on %F at %R"
done
With find
Very likely your find has a rich -printf option:
find . -maxdepth 1 -name '*Des*' -printf 'The file %f was modified on %TY-%Tm-%Td at %TH:%TM\n'
I want to use stat
(because your date doesn't handle the -r switch, you don't want to use find or just because you like using as most tools as possible to impress your little sister). Well, in that case, the safest thing to do is:
date -d "#$(stat -c '%Y' Desktop)" +"The file Desktop was modified on %F at %R"
and with your glob requirement (in Bash):
shopt -s nullglob
for file in *Des*; do
date -d "#$(stat -c '%Y' -- "$file")" +"The file ${file//%/%%} was modified on %F at %R"
done
stat -c "The file "%n" was modified on ""%y" *Des* | awk 'BEGIN{OFS=" "}{for(i=1;i<=7;++i)printf("%s ",$i)}{print "at " substr($8,0,6)}'
I have use here awk modify your code. what i have done in this code, from field 1,7 i printed it using for loop, i need to modify field 8, so i used substr to extract 1st 5 character.

Shell Script to check the folder created date against the current date/time

I am preparing shell script if folder created date is equal to the current date/time then it need to call the another script .
My requirement is script need to check only the folder created date against the current date/time not to the files date/time inside the folder .
Thanks in advance
You can have a look at the stat command and the change time of the folder. The change time gives the last date when the metadata of the folder was changed. (stackexchange link). Timestamps of permission changes are also included in this timestamp. This is maybe not exactly what you need.
For the current time, you can use the date command. You can compare timestamps between the stat and the date command if you print the output in seconds since the epoch.
stat --format="%Z" /path/to/folder
date +%s
Suppose TestToday is your Directory Name
*Please replace TestToday with your directory name in below script
Test.sh
ls -lrt | grep ^d | grep TestToday | grep "`date +%b`" | awk -v var="`date +%d | bc`" '$7==var {print $NF}' > DIR_NAME
DIR_EXISTS=`cat DIR_NAME`
#echo $DIR_EXISTS
if [ "$DIR_EXISTS" == "TestToday" ];then
echo "Calling Shell Script Here."
else
echo "Directed not created or updated today."
fi

Get mtime of specific file using Bash?

I am well aware of being able to do find myfile.txt -mtime +5 to check if my file is older than 5 days or not. However I would like to fetch mtime in days of myfile.txt and store it into a variable for further usage. How would I do that?
stat can give you that info:
filemtime=$(stat -c %Y myfile.txt)
%Y gives you the last modification as "seconds since The Epoch", but there are lots of other options; more info. So if the file was modified on 2011-01-22 at 15:30 GMT, the above would return a number in the region of 1295710237.
Edit: Ah, you want the time in days since it was modified. That's going to be more complicated, not least because a "day" is not a fixed period of time (some "days" have only 23 hours, others 25 — thanks to daylight savings time).
The naive version might look like this:
filemtime=$(stat -c %Y "$1")
currtime=$(date +%s)
diff=$(( (currtime - filemtime) / 86400 ))
echo $diff
...but again, that's assuming a day is always exactly 86,400 second long.
More about arithmetic in bash here.
The date utility has a convenient switch for extracting the mtime from a file, which you can then display or store using a format string.
date -r file "+%F"
# 2021-01-12
file_mtime=$(date -r file "+%F")
See man date, the output of date is controlled by a format string beginning with "+"
Useful format strings for comparing many dates might include:
"+%j": day of year
"+%s": unix epoch time
Arithmetic with dates is a bit of a pain in bash, so if you need relative time that will work in all corner cases, you may be better off with another language.
AGE=$(perl -e 'print -M $ARGV[0]' $file)
will set $AGE to the age of $file in days, as Perl's -M operator handles the stat call and the conversion to days for you.
The return value is a floating-point value (e.g., 6.62849537 days). Add an int to the expression if you need to have an integer result
AGE=$(perl -e 'print int -M $ARGV[0]' $file)
Ruby and Python also have their one-liners to stat a file and return some data, but I believe Perl has the most concise way.
I this the answer?
A=$(stat -c "%y" myfile.txt)
look at stat-help
stat --help
Usage: stat [OPTION]... FILE...
Display file or file system status.
[...]
-c --format=FORMAT use the specified FORMAT instead of the default;
output a newline after each use of FORMAT
[...]
The valid format sequences for files
[...]
%y Time of last modification, human-readable
%Y Time of last modification, seconds since Epoch
[...]

Resources