Get files in bash script that contain an underscore
In a directory with a bunch of files that look like this:
./test1_November 08, 2014 AM.flv
./test2.flv
./script1.sh
./script2.sh
I want to process only files that have an .flv extension and no underscore. I'm trying to eliminate the files with underscores without much luck.
bash --version
GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
script:
#!/bin/bash
FILES=$(find . -mtime 0)
for f in "${FILES}"
do
if [[ "$f" != *_* ]]; then
echo "$f"
fi
done
This gives me no files. Changing the !=
to ==
gives me all files instead of just those with an underscore. Other answers on SO indicate this should work.
Am I missing something simple here?
You can use this extended glob pattern:
shopt -s extglob
echo +([^_]).flv
+([^_])
will match 1 or more of any non underscore character.
Testing:
ls -l *flv
-rw-r--r-- 1 user1 staff 0 Nov 8 12:44 test1_November 08, 2014 AM.flv
-rw-r--r-- 1 user1 staff 0 Nov 8 12:44 test2.flv
echo +([^_]).flv
test2.flv
To process these files in a loop use:
for f in +([^_]).flv; do
echo "Processing: $f"
done
PS: Not sure you're using -mtime 0
in your find
as my answer is for the requiremnt:
I want to process only files that have an .flv extension and no underscore
You can pass multiple patterns to find
and include a not
find . -name "*.flv" -not -name "*_*"
You can loop over the results of find
by piping it into a while
find -name "*.flv" -not -name "*_*" -print0 | while IFS= read -r -d '' filename; do
echo "$filename"
done
or you can forgo the loop completely and use xargs
find -name "*.flv" -not -name "*_*" -print0 | xargs -0 -n1 echo
The problem is this line:
for f in "${FILES}"
The quotes are preventing word splitting, so entire list of filenames is being processed as a single item. What you want is:
IFS=$'n'
for f in $FILES
The IFS
setting makes it use newlines as the word delimiters, so you can have filenames with spaces in them.
A better way to write loops like this is to avoid using the variable:
find ... | while read -r f
do
...
done
链接地址: http://www.djcxy.com/p/36210.html
上一篇: VIEW无效(程序包安装程序已停止)
下一篇: 在bash脚本中获取包含下划线的文件