I've been trying to match all file names in a directory that are 6 characters long and only contain digits. I've been banging my head trying to get it to work but with no luck. This is what I have:
for f in "$path"*
do
if echo "$f" | tail -c 7 | grep "^[[:digit:]][:digit:]]*$"; then
echo "$f is good"
else
echo "$f" | tail -c 7
fi
done
Every time I run the script the else gets ran and I just get the last 6 characters from each file in the directory. I don't want to have to cd into the directory to check the files so I thought taking the last 6 and checking would be a good idea (maybe not). I want to eventually redirect all files in $path that are 6 characters long and all digits. I just cant figure out how to match this. Thank you!
here is a one liner to just list the filenames:
for f in "$path"[0-9][0-9][0-9][0-9][0-9][0-9];do echo ${f##*/};done
if you want the full path just omit the ##*/
ls [0-9][0-9][0-9][0-9][0-9][0-9]
Or, if you simply want to edit your script:
for f in "$path"*
do
if echo "$f" | tail -c 7 | grep "^[[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]]$"; then
echo "$f is good"
else
echo "$f" | tail -c 7
fi
done
Or, just use the regex pattern:
'^[[:digit:]]{6}$'
Use basename
to get the filename part of a pathname, and test that:
for f in "$path"*
do
base=$(basename "$f")
case "$base" in
[0-9][0-9][0-9][0-9][0-9][0-9])
echo "$f is good" ;;
*) echo "$base" ;;
esac
done
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.