text processing - Extract certain part of filename in Bash -
i have many files in folder:
yyyymmdd_hhmmss.mp4 yyyymmdd_hhmmss_suffix1.mp4 yyyymmdd_hhmmss_suffix1_suffix2.mp4
the following filename formats possible (rarely):
yyyymmdd_hhmmss_$$$.mp4 yyyymmdd_hhmmss_$$$_suffix1.mp4 yyyymmdd_hhmmss_$$$_suffix1_suffix2.mp4 yyyymmdd_hhmmss_$$.mp4 yyyymmdd_hhmmss_$$_suffix1.mp4 yyyymmdd_hhmmss_$$_suffix1_suffix2.mp4 yyyymmdd_hhmmss_$.mp4 yyyymmdd_hhmmss_$_suffix1.mp4 yyyymmdd_hhmmss_$_suffix1_suffix2.mp4
where $ number 0-9
i trying catch "yyyymmdd_hhmmss" , use argument. when 1 suffix presented:
for file in "$@"; file_nosuffix="${file%*_suffix1.mp4}.mp4" echo "$file , $file_nosuffix" done
but lost when sorts of filename formats mentioned above presented. ideally stick current pattern:
for file in "$@"; #catch "yyyymmdd_hhmmss" #do on files yyyymmdd_hhmmss.mp4 #do else on files yyyymmdd_hhmmss_suffix1.mp4 #etc. done
is possible?
bash has built-in regex support, if want confirm format:
regex='^[[:digit:]]{8}_[[:digit:]]{6}' # posix ere; can't use pcre extensions here file; if [[ $file =~ $regex ]]; echo "${bash_rematch[0]} substring $file" >&2 else echo "$file match required format" >&2 fi done
one can trivially take prefix;
for file; prefix=${file:0:15} echo "prefix $file $prefix" done
...or, delete last 2 underscores , after them:
prefix=${file%_*_*}
see:
- bashfaq #100 ("how can string manipulations in bash?")
- parameter expansion
Comments
Post a Comment