Script to locate date in filename

I am looking for a way to find a date in the file without using find. for example something like this:

files=`ls |grep txt`
YEST=`TZ="GMT+24" date +'%m-%d-%Y'|sed 's/^0//g' |sed 's/$/.txt/g'`
YES1=`TZ="GMT+48" date +'%m-%d-%Y'|sed 's/^0//g' |sed 's/$/.txt/g'`
if [[ $files = "5-28-2014" ]]; then echo yes;else echo no;fi

There are a number of files that have 5-28-2014.txt in the name, even one file that is named just 5-28-2014.txt, but I keep getting "no" when the script returns the value. Any ideas?

Also the YEST variable does contain 5-28-2014.txt, I echoed to check it

if [[ $files == "5-28-2014" ]]; then echo yes;else echo no;fi

In bash, use regexp comparison operator:

#!/bin/bash

for file in *.txt
do
        [[ "$file" =~ "5-28-2014" ]] && echo "yes" || echo "no"
done

Its not clear for me, about your aim, sorry if I misunderstood

try

if grep "5-28-2014" <(ls *.txt)>/dev/null; then echo yes; else echo no;fi

if grep "5-28-2014" <<<$(ls *.txt)>/dev/null; then echo yes; else echo no;fi
1 Like

First, note that the two lines marked in red above make absolutely no difference to the following if statement. The variables you define on those lines are not referenced after they are defined.

Second, if we supposed that you have two files named with names containing "txt", say for instance 5-28-2014.txt and txtfile . In this case the 1st line of your script sets the variable files to the value:

5-28-2014.txt
txtfile

The last line in your script then compares this two line value to the string "5-28-2014" and will find (even after changing the = to == ) that the strings "5-28-2014.txt\ntxtfile" and "5-18-2014" are not the same.

Yoda already suggested a way around this assuming you are looking for the date in the file's name. You could also try something like the following for that:

for file in *5-28-2014*.txt
do
        [ "$file" = "*5-28-2014*.txt" ] && echo 'no' && break
        printf "process file: %s\n" "$file"
done

which will work with any shell that recognizes basic POSIX standard shell syntax.

If you're looking for the date as text inside a file, rather than in the file's name, Akshay suggested a way to do that.

1 Like