简体   繁体   中英

Using regular expression to search for a specific pattern in UNIX

I have file names like ABCD20140207090842 ABCD20140207090847 ABCD20140207090849 ABCD20140207090850 ABCD2014556644219268 ABCD20140508525691 tf in my directory.

I want to search for files with specific pattern. ie FileNameYearMonthDayHourMinSec.txt

Note: files tf and ABCD2014556644219268 should not get matched.

Answer with exact pattern would be appreciated.

Based on NAME, followed by DATE.txt I get this:

find . -regex ".*[19|20][0-9][0-9][0-1][0-2][0-3][0-9][0-2][0-9][0-6][0-9][0-6][0-9]\.txt$"

This doesn't account for leap-years though, and could match dates such as 31 Feb.

Change the idea. Here is the script no matter leap years or not.

Using GNU date to identify the date

for file in *.txt
do
  time=${file%.*}         # remove suffix and get ABCD20140207090842 
  time=${time:(-14)}      # get the date/time 20140207090842
  time="${time:0:4}/${time:4:2}/${time:6:2} ${time:8:2}:${time:10:2}:${time:12}"      # convert time to: 2014/02/07 09:08:42
  date -d "$time" >/dev/null 2>&1 && echo $file
done

ABCD20140207090842.txt
ABCD20140207090847.txt
ABCD20140207090849.txt
ABCD20140207090850.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM