[bash]查找指定目录下符合格式的txt文件
需求:
查找指定目录下符合yyyy-MM-dd(-b)NNN.txt格式的文件,如“2020-03-22-b888.txt”
目标目录内容:
[root@localhost bashs]# ll /root/testfolder total 0 -rw-r--r--. 1 root root 0 Mar 22 03:31 2015-04-15-b123.txt -rw-r--r--. 1 root root 0 Mar 22 03:31 2019-03-21-b123.txt drwxr-xr-x. 2 root root 6 Mar 21 06:53 2020 drwxr-xr-x. 2 root root 6 Mar 21 06:16 2020-01-10-b001 drwxr-xr-x. 2 root root 6 Mar 21 06:16 2020-02-20-b001 drwxr-xr-x. 2 root root 6 Mar 21 06:16 2020-03-20-b001 drwxr-xr-x. 2 root root 6 Mar 21 06:15 2020-03-21-b001 -rw-r--r--. 1 root root 0 Mar 22 03:31 2020-03-21-b123.txt drwxr-xr-x. 2 root root 6 Mar 21 06:15 2020-03-22-b001 -rw-r--r--. 1 root root 0 Mar 22 03:31 2020-03-22-b123.txt drwxr-xr-x. 2 root root 6 Mar 21 06:50 2020-20 drwxr-xr-x. 2 root root 6 Mar 21 06:16 archive -rw-r--r--. 1 root root 0 Mar 21 06:18 a.txt drwxr-xr-x. 2 root root 6 Mar 21 06:16 backup -rw-r--r--. 1 root root 0 Mar 21 06:18 b.txt
期待结果:
2015-04-15-b123.txt 2020-03-22-b123.txt a.txt 2019-03-21-b123.txt
代码:
#!/bin/bash function findFilesUnder(){ folder=$1 for file in `find $folder -type f -regextype 'posix-egrep' -regex $folder+'/[0-9]{4}-[0-9]{2}-[0-9]{2}-b[0-9]{3}.txt$'`; do echo $file done } findFilesUnder "/root/testfolder"
执行结果:
[root@localhost bashs]# sh files.sh /root/testfolder/2020-03-22-b123.txt /root/testfolder/2020-03-21-b123.txt /root/testfolder/2019-03-21-b123.txt /root/testfolder/2015-04-15-b123.txt [root@localhost bashs]#
--2020年3月22日--