I have a for loop that recursively searches a directory for files.
for FILE in $(find /home/mydir/ -name '*.txt' -or -name '*.zip')
They have the following format:
/home/mydir/subdir1/subdir2/22280317.txt
I want to extract the 6 numbers left of the .txt
as the date in the format 2017-03-28
I've tried using awk
however am having trouble as there are two digits at the start that I want to ignore
This may solve your problem
find -name "*.txt" -exec sh -c 'f=${0%.txt}; l6=${f: -6}; date -d "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d" ' {} \;
Test Results
# create sample files
[akshay@localhost test]$ touch 10280317.txt
[akshay@localhost test]$ touch 10170317.txt
[akshay@localhost test]$ touch 10170398.txt
# files created
[akshay@localhost test]$ ls *.txt
10170317.txt 10170398.txt 10280317.txt
# output using date command which takes care of year
# remove .txt
# extract last 6 char
# input year-mon-date to date command
[akshay@localhost test]$ find -name "*.txt" -exec bash -c 'f=${0%.txt}; l6=${f: -6}; date -d "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d" ' {} \;
2017-03-28
2017-03-17
1998-03-17
In case if you want to display filename along with date then
[akshay@localhost tmp]$ pwd
/tmp
[akshay@localhost tmp]$ find -name "*.txt" -exec bash -c 'f=${0%.txt}; l6=${f: -6}; echo $f $(date -d "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d") ' {} \;
./tss/test/10280317 2017-03-28
./tss/test/10170317 2017-03-17
./tss/test/10170398 1998-03-17
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments