LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 10-26-2018, 06:11 PM   #1
rwyarbrough
Member
 
Registered: Oct 2003
Location: Mesquite, Texas
Distribution: Slackware_x64 15.0 and slackware-current
Posts: 33

Rep: Reputation: 2
Bash case-esac alternatives and optimization for empty and set variable combinations


Below is a piece of working code in a much larger program that basically renames directories containing music files before performing some other tasks.
My question is if there is a way to optimize this using less code, a case-esac block or any other methods I haven't thought about?

Any suggestions on how to tighten up the code for the debugger is also welcomed. Thanks in advance

Code:
find -type d -maxdepth 1 | while read R; # loop through album directories to get mp3 names
DNAME=$R
#
# gathered release date, recorded date, album name, and bitrate from one audio file in directory using mediainfo
# if mediainfo can't find an album name, I aborted during the gathering phase to prevent strange directory names
#
NEWDIRNAME=$DIRRELEASED.$DIRALBUM.$DIRRATE # Desired directory name = [ -n "$DIRRELEASED" ] && [ -n "$DIRALBUM" ] && [ -n "$DIRRATE" ]
if [ "$NEWDIRNAME" != "$DNAME" ] 	# only execute code if the new name is different than existing name - first check
then
	if [ -z "$DIRRELEASED" ] && [ -z "$DIRRECORDED" ] && [ -n "$DIRALBUM" ] && [ -z "$DIRRATE" ]
	then
		NEWDIRNAME=$DIRALBUM
	fi
	if [ -n "$DIRRELEASED" ] && [ -n "$DIRALBUM" ] && [ -z "$DIRRATE" ]
	then
		NEWDIRNAME=$DIRRELEASED.$DIRALBUM
	fi
	if [ -z "$DIRRELEASED" ] && [ -z "$DIRRECORDED" ] && [ -n "$DIRALBUM" ] && [ -n "$DIRRATE" ]
	then
		NEWDIRNAME=$DIRALBUM.$DIRRATE
	fi
	if [ -z "$DIRRELEASED" ] && [ -n "$DIRRECORDED" ] && [ -n "$DIRALBUM" ] && [ -n "$DIRRATE" ]
	then
		NEWDIRNAME=$DIRRECORDED.$DIRALBUM.$DIRRATE
	fi
	if [ -z "$DIRRELEASED" ] && [ -n "$DIRRECORDED" ] && [ -n "$DIRALBUM" ] && [ -z "$DIRRATE" ]
	then
		NEWDIRNAME=$DIRRECORDED.$DIRALBUM
	fi
	#
	if [ "$DEBUG" = "debug" ]
	then
		if [ "$NEWDIRNAME" != "$DNAME" ] # only execute code if the new name is different than existing name - final check after gathering and updating
		then
			mv -v -f $DNAME $NEWDIRNAME | tee -a $DEBUGLOG $RENAMELOG
		else
			echo "directory $DNAME doesn't need renaming" | tee -a $DEBUGLOG $RENAMELOG
		fi
	else
		if [ "$NEWDIRNAME" != "$DNAME" ] # only execute code if the new name is different than existing name - final check after gathering and updating
		then
			mv -v -f $DNAME $NEWDIRNAME | tee -a $RENAMELOG
		else
			echo "directory $DNAME doesn't need renaming" | tee -a $DEBUGLOG $RENAMELOG
		fi
	fi	
else
	if [ "$DEBUG" = "debug" ]
	then
		echo "directory $DNAME doesn't need renaming" | tee -a $DEBUGLOG $RENAMELOG
	else
		echo "directory $DNAME doesn't need renaming" | tee -a $RENAMELOG
	fi
fi

Last edited by rwyarbrough; 10-26-2018 at 06:52 PM.
 
Old 10-26-2018, 08:01 PM   #2
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: Somewhere in my head.
Distribution: Slackware (15 current), Slack15, Ubuntu studio, MX Linux, FreeBSD 13.1, WIn10
Posts: 10,342

Rep: Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242
here is one way I've moved my mp3 renaming the dir/sub-dir by meta tags, its old bash code, but it works.
Code:
#!/bin/bash


#sort move mp3s into respective directories.
#Date written 
#Tur Dec 29, 2016

#set -x

typeset -i count max sum1 sum2 


working_path="/run/media/userx/250GB"

move_to="/run/media/userx/250GB/MUSIC2"

sum1="$(find "$working_path" -type f -iname "*.mp3" | wc -l)"
#sum2="$(find "$working_path" -type f -iname "*.flac" | wc -l)"

#max=$(($sum1+$sum2))

max="$sum1"

find "$working_path" -type f -iname "*.mp3" | while [[ $count -le $max ]] ; do
read FILENAME;

 

 c=$FILENAME
 xpath=${c%/*} 
 xbase=${c##*/}
 
 xfext=${xbase##*.}
 xpref=${xbase%.*}
 
 path=${xpath}
 fname=${xpref}
 ext=${xfext}
 
#############################################################
#get the metadata tags off the mp3's using exiftool-perl
#################

if [[ "${ext}" -eq 'mp3' ]] ; then

ARTIST="`exiftool -Artist "$FILENAME" -p '$Artist'`"
TITLE="`exiftool -Title  "$FILENAME" -p '$Title'`"
ALBUM="`exiftool -Album  "$FILENAME" -p '$Album'`"

#ensure only one space between each word
ARTIST="$(echo -e "${ARTIST}" | sed -e 's/\s+/ /g')"

TITLE="$(echo -e "${TITLE}" | sed -e 's/\s+/ /g')"
 
ALBUM="$(echo -e "${ALBUM}" | sed -e 's/\s+/ /g')"

#removes leading white space on both ends of string
ARTIST="$(echo -e "${ARTIST}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
TITLE="$(echo -e "${TITLE}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
ALBUM="$(echo -e "${ALBUM}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"

if [[ -n "$ARTIST" ]] && [[ -n "$ALBUM" ]] && [[ -n "$TITLE" ]] && [[ -d "$move_to"/"$ARTIST"/"$ALBUM" ]] ; then
	mv -v "${FILENAME}" "$move_to"/"$ARTIST"/"$ALBUM"
		elif [[ -n "$ARTIST" ]] && [[ -n "$ALBUM" ]] && [[ -n "$TITLE" ]] && [[ ! -d "$move_to"/"$ARTIST"/"$ALBUM" ]] ; then
			mkdir -pv "$move_to"/"$ARTIST"/"$ALBUM"
			mv -v "${FILENAME}" "$move_to"/"$ARTIST"/"$ALBUM"
		
fi
echo;echo;echo;echo

echo "MAX   is $max"
((count++))
fi
echo "count is $count"
left=$(expr $max - $count)
echo "         --------"
echo "         $left"
echo


done
here is a different one,
Code:
#!/bin/bash

working_dir="/run/media/userx/4TB_esaystore/Music"  
move_to="/run/media/userx/4TB_esaystore/Resampled_Music" 
script_dir=/home/userx/scripts
no_tags=/run/media/userx/4TB_esaystore/music_no_tags
orginals=/run/media/userx/4TB_esaystore/orginal_music

manyfiles="$(find "$working_dir" -type f -name "*.mp3" -o -name "*.Mp3" -o -name "*.MP3" -o -name "*.flac" | wc -l)"

while read FILE ; do 
	c=$FILE
	xpath=${c%/*} 
	xbase=${c##*/}
	xfext=${xbase##*.}
	xpref=${xbase%.*}
	path=${xpath}
	pref=${xpref}
	ext=${xfext}

	newFile="$pref"."mp3"

	#removes and replaces leaving the band directroy and its subdirectories
	#to put the resmaped music into
	NoTags=${path/$working_dir/$no_tags}
	keep_orginals=${path/$working_dir/$orginals}
	
	bitrate="$(exiftool -p '$AudioBitrate' "$FILE")"
	#strips kpbs
	bitrate=${bitrate% *}
	echo "$bitrate"
# set check bitrate values low / high
rate2l=128
rate2h=128
	artist="$(exiftool -p '$Artist' "$FILE")"
	album="$(exiftool -p '$Album' "$FILE")"
	title="$(exiftool -p '$Title' "$FILE")"
	genre="$(exiftool -p '$Genre' "$FILE")"
##############################################################
# Resampling with LAME 99.9.5  
# if MP3 is out of limits then re-sample it if not then send it through
# skip resampling saves time
###
# flac -cd "$f" | lame -b 320 - "${f%.*}".mp3
if [[ "${ext}" == 'flac' ]] ; then
{
		echo "got Dflack file  $ext"
		
		
		flac -cd "$FILE" | lame -V2 -b 128  -F --vbr-new -m j -q 2  - "$newFile"
		 
		#rm -v "$FILE"
		
		mid3v2 -a "$artist"  "$script_dir"/"$newFile"
		mid3v2 -A "$album"  "$script_dir"/"$newFile"
		mid3v2 -t "$title"  "$script_dir"/"$newFile"
		mid3v2 -g "$genre" "$script_dir"/"$newFile"
		
		if [[ -n "$artist" && -n "$album" ]] ; then
		{
			NewPath2="$move_to"/"$artist"/"$album"
			mkdir -p "$NewPath2"
			
			mv -vf "$script_dir"/"$newFile" "$NewPath2"
			
			echo;echo "moving orginal"
			mkdir -pv "$keep_orginals"
			mv -vf "$FILE" "$keep_orginals"
			echo;echo "orginal moved"
		}
		else
		{
			mkdir -p "$NoTags"
			mv -vf "$script_dir"/"$newFile" "$NoTags"
			
				
			echo;echo "moving orginal"
			mkdir -pv "$keep_orginals"
			mv -vf "$FILE" "$keep_orginals"
			echo;echo "orginal moved"
		}
		fi
} # if  start bitrate  <    128     or   start bitrate > 160 then resample
elif [[ "${bitrate%.*}" -gt "${rate2h}" ]] ; then
{
	lame -V2 -b 128  -F --vbr-new -m j -q 2 "$FILE" "$newFile"
	mid3v2 -a "$artist"  "$script_dir"/"$newFile"
	mid3v2 -A "$album"  "$script_dir"/"$newFile"
	mid3v2 -t "$title"  "$script_dir"/"$newFile"
	mid3v2 -g "$genre" "$script_dir"/"$newFile"
	
	if [[ -n "$artist" && -n "$album" ]] ; then
	{
		NewPath2="$move_to"/"$artist"/"$album"
		mkdir -p "$NewPath2"
		mv -vf "$script_dir"/"$newFile" "$NewPath2"
						
		echo;echo "moving orginal"
		mkdir -pv "$keep_orginals"
		mv -vf "$FILE" "$keep_orginals"
		echo;echo "orginal moved"
	}
	else
	{
		mkdir -p "$NoTags"
		mv -vf "$script_dir"/"$newFile" "$NoTags"
			
		echo;echo "moving orginal"
		mkdir -pv "$keep_orginals"
		mv -vf "$FILE" "$keep_orginals"
		echo;echo "orginal moved"
	}
	fi
}
elif [[  -n "$artist" && -n "$album" ]] ; then
{
			NewPath2="$move_to"/"$artist"/"$album"
			mkdir -p "$NewPath2"
			mv -vf "$FILE" "$NewPath2"
}
else
{
	mkdir -p "$NoTags"
	mv -vf "$script_dir"/"$newFile" "$NoTags"
	
	echo;echo "moving orginal"
	mkdir -pv "$keep_orginals"
	mv -vf "$FILE" "$keep_orginals"
	echo;echo "orginal moved"
}
fi  
echo;echo;echo;echo "counting down $((manyfiles--))"
#done <<<"$(find "$working_dir"  "$working_dir2"  -type f -name "*.mp3" -o -name "*.Mp3" -o -name "*.MP3" -o -name "*.flac" )"
done <<<"$(find "$working_dir"  -type f -name "*.mp3" -o -name "*.Mp3" -o -name "*.MP3" -o -name "*.flac" )"
it can get harry doing this, these are my less elaborate ones.

Last edited by BW-userx; 10-26-2018 at 08:06 PM.
 
Old 10-26-2018, 09:58 PM   #3
rwyarbrough
Member
 
Registered: Oct 2003
Location: Mesquite, Texas
Distribution: Slackware_x64 15.0 and slackware-current
Posts: 33

Original Poster
Rep: Reputation: 2
Quote:
Originally Posted by BW-userx View Post
here is one way I've moved my mp3 renaming the dir/sub-dir by meta tags, its old bash code, but it works.
Thanks! I have a script that performs mkvnixtool operations on recursive directories so I can have consistency ( and fancy titles) with my TV_show downloads - fun stuff!

Quote:
Originally Posted by BW-userx View Post
it can get harry doing this, these are my less elaborate ones.
Take a peek at this... ( debugger code removed to reduce length of post - you're welcome very much! <grin>

The reasoning for all this is that I like to include the bitrate information in the directory and file names. This only works with compressed audio, so I just use the extension in place of the bitrate in the directory/filename for uncompressed, Lossless, and unknown file types.

Code:
AUDIOFORMATS=(.3gp .aa .aac .aax .act .aiff .amr .ape .au .awb .bwf .dct .dss .dvf .flac .gsm .iklax .ivs .m4a .m4b .m4p .mmf .mp3 .mpc .msv .nsf .ogg .oga .mogg .opus .pcm .ra .rm .raw .sln .tta .vox .wav .wma .wv .webm .8svx)
# Audio Types - X = unknown or excluded C = Compressed L = Lossless U = Uncompressed
AUDIOFORMATTYPES=(X X C X X U X L U X L X X X L X X X C C C X C C X X C X X X U X X U X X X U C X C X)
function buildaudioformatfind()
{
	# build audio file type array
	for i in "${!AUDIOFORMATTYPES[@]}"
	do
		if [[ "${AUDIOFORMATTYPES[$i]}" = "C" ]]
		then
			COMPRESSEDAUDIO=("${COMPRESSEDAUDIO[@]}" "${AUDIOFORMATS[$i]}")
		else
			UNCOMPRESSEDAUDIO=("${UNCOMPRESSEDAUDIO[@]}" "${AUDIOFORMATS[$i]}")
		fi
	done
	# creating find strings from audio file type arrays created above
	for index in ${!COMPRESSEDAUDIO[@]}
	do
		FINDVAR=(${FINDVAR[@]} $(printf '%s \"*%s\" %s' "-name" ${COMPRESSEDAUDIO[$index]}  "-o") )
		L=$(echo ${#FINDVAR[@]})
		FINDSTRING=$(echo ${FINDVAR[@]:0:$L} | sed 's/\(.*\)-o.*/\1/')
	done
	for index in ${!UNCOMPRESSEDAUDIO[@]}
	do
		FINDVARU=(${FINDVARU[@]} $(printf '%s \"*%s\" %s' "-name" ${UNCOMPRESSEDAUDIO[$index]}  "-o") )
		L=$(echo ${#FINDVARU[@]})
		FINDSTRINGU=$(echo ${FINDVARU[@]:0:$L} | sed 's/\(.*\)-o.*/\1/')
	done
	FINDVARFULL=(${FINDVAR[@]} ${FINDVARU[@]})
	L=$(echo ${#FINDVARFULL[@]})
	FINDSTRINGFULL=$(echo ${FINDVARFULL[@]:0:$L} | sed 's/\(.*\)-o.*/\1/')
}

Last edited by rwyarbrough; 10-26-2018 at 10:02 PM.
 
Old 10-27-2018, 06:38 AM   #4
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,783

Rep: Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083Reputation: 2083
Quote:
Originally Posted by rwyarbrough View Post
Below is a piece of working code
I think you're missing the do done for the while loop actually.

Quote:
My question is if there is a way to optimize this using less code, a case-esac block or any other methods I haven't thought about?
So if I understand correctly, you have 4 variables, and you want to join them together with dots in between, leaving out empty variables. I would go with something like this:

Code:
[ -n "$DIRRELEASED"	] && NEWDIRNAME+="$DIRRELEASED".
[ -n "$DIRRECORDED"	] && NEWDIRNAME+="$DIRRECORDED".
[ -n "$DIRALBUM"	] && NEWDIRNAME+="$DIRALBUM".
[ -n "$DIRRATE"		] && NEWDIRNAME+="$DIRRATE".
NEWDIRNAME=${NEWDIRNAME:0:-1} # chop off trailing dot.
Quote:
Originally Posted by rwyarbrough View Post
Take a peek at this... ( debugger code removed to reduce length of post - you're welcome very much! <grin>
Just some general comments

Code:
ARRAY_VAR=("${ARRAY_VAR[@]}" "$VALUE")
# can be written
ARRAY_VAR+=("$VALUE")

for i in ${!ARRAY_VAR[@]}
   ... ${ARRAY_VAR[i]} ...
# can be written
for elem in "${ARRAY_VAR[@]}"
   ... $elem ...

L=$(echo ${#FINDVAR[@]})
# is just
L=${#FINDVAR[@]}
 
2 members found this post helpful.
Old 10-28-2018, 04:27 AM   #5
mina86
Member
 
Registered: Aug 2008
Distribution: Debian
Posts: 517

Rep: Reputation: 229Reputation: 229Reputation: 229
Your code does not handle case when DIRALBUM is not set so I’m assuming that it’s always set. There are a few other approaches:

Code:
NEWDIRNAME=${DIRRELEASED:-DIRRECORDED}.$DIRALBUM.$DIRRATE
NEWDIRNAME=${NEWDIRNAME#.}  # remove leading dot if date is missing
NEWDIRNAME=${NEWDIRNAME%.}  # remove leading dot if bitrate is missing
or:

Code:
date=${DIRRELEASED:-$DIRRECORDED}
NEWDIRNAME=$date${date:+.}$DIRALBUM${DIRRATE:+.}$DIRRATE

Quote:
Originally Posted by rwyarbrough View Post
Code:
			mv -v -f $DNAME $NEWDIRNAME | tee -a $DEBUGLOG $RENAMELOG
Don’t forget to quote your variables.
 
1 members found this post helpful.
Old 10-28-2018, 02:17 PM   #6
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: Somewhere in my head.
Distribution: Slackware (15 current), Slack15, Ubuntu studio, MX Linux, FreeBSD 13.1, WIn10
Posts: 10,342

Rep: Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242
@rwyarbrough, how do you scrape your mp3's to get the meta data off it, album, artist, title? using exiftool I have to run that over the mp3 for each tag, which means three times or more depending on meta data tag info I am trying to get. I was wondering what it your method, if it is more economical.
 
Old 10-31-2018, 01:53 PM   #7
rwyarbrough
Member
 
Registered: Oct 2003
Location: Mesquite, Texas
Distribution: Slackware_x64 15.0 and slackware-current
Posts: 33

Original Poster
Rep: Reputation: 2
Quote:
Originally Posted by BW-userx View Post
@rwyarbrough, how do you scrape your mp3's to get the meta data off it, album, artist, title?
For the directory renaming, I use mediainfo https://mediaarea.net/en/MediaInfo - Multiplatform - quite a nice program. it has quite a few fields, but you can run it once and parse the desired fields.
example output
Quote:
>$ mediainfo 14_Enigma_Variationen_-_XIII.Romanza-_---_Moderato.mp3
General
Complete name : 14_Enigma_Variationen_-_XIII.Romanza-_---_(Moderato).mp3
Format : MPEG Audio
File size : 6.44 MiB
Duration : 2 min 48 s
Overall bit rate mode : Constant
Overall bit rate : 320 kb/s
Album : Enigma Variation & Pomp and Circumstance op39
Album/Performer : Edwin Elgar
Track name : Enigma Variationen - XIII.Romanza: *** (Moderato)
Track name/Position : 14
Performer : Edwin Elgar
Genre : classical
Recorded date : 1985
Writing library : LAME3.99r

Audio
Format : MPEG Audio
Format version : Version 1
Format profile : Layer 3
Format settings : Joint stereo
Mode : Joint stereo
Duration : 2 min 48 s
Bit rate mode : Constant
Bit rate : 320 kb/s
Channel(s) : 2 channels
Sampling rate : 44.1 kHz
Compression mode : Lossy
Stream size : 6.43 MiB (100%)
Writing library : LAME3.99r
Encoding settings : -m j -V 4 -q 3 -lowpass 20.5

For the actual file renaming, I use filebot (which I think also uses mediainfo as a call)

pi.pad(2) = track number padded to 2 digits
t.space('_') = Track Name with spaces replaced by underscores (along with other replacements)
$media.OverallBitrateString = overall bite rate
media.overallBitrateString will return the kbps value of the digital recording unless its a variable bitrate digital recording which will return "null", so I replace null with the word variable.

filebot rename code
Code:
# file renaming starts here
	#Track name
	CNT=0
	for f in ${COMPRESSEDFILESARRAY[*]}
	do
		CNT=$(( CNT + 1 ))
		if [ "$DEBUG" = "debug" ]
		then
			echo "renaming with command: filebot -rename $f --format \"{pi.pad(2)}.{t.space('_').replaceAll(/&/,\"and\").replaceAll(/#/,\"number\").replaceAll(\"[^a-zA-ZÀ-ÿ0-9_-]\", \"\")}{\".\$media.OverallBitrateString\".replaceAll(/null/, \"variable\").replaceAll(/ kb\/s/,\"\")}\" --db $DBID  >> $DEBUGLOG" >> $DEBUGLOG
			filebot -rename $f --format "{pi.pad(2)}.{t.space('_').replaceAll(/&/,\"and\").replaceAll(/#/,\"number\").replaceAll(\"[^a-zA-ZÀ-ÿ0-9_-]\", \"\")}{\".\$media.OverallBitrateString\".replaceAll(/null/, \"variable\").replaceAll(/ kb\/s/,\"\")}" --db $DBID >> $DEBUGLOG
			echo "the filename is = $f" >> $DEBUGLOG
		else
			filebot -rename $f --format "{pi.pad(2)}.{t.space('_').replaceAll(/&/,\"and\").replaceAll(/#/,\"number\").replaceAll(\"[^a-zA-ZÀ-ÿ0-9_-]\", \"\")}{\".\$media.OverallBitrateString\".replaceAll(/null/, \"variable\").replaceAll(/ kb\/s/,\"\")}" --db $DBID >> $RENAMELOG
		fi
		fcut=$(echo ${f##*/} | cut -c -30)
				printf "\r%b" "\033[2K"
				printf "%3d %% completed - %5d of %5d - %s" "$(($CNT*100/$AUDIODIRCOUNT))" "$CNT" "$AUDIODIRCOUNT" "$fcut"
		#echo -en "$(($CNT*100/$AUDIODIRCOUNT))% completed - $CNT of $AUDIODIRCOUNT - $fcut \r"
	done
	# uncompressed starts here
	echo -e "\n************************************************************"
	echo -e "\nthis run for uncompressed audio files"
	echo "There are $AUDIODIRCOUNTU uncompressed audio files in $dircountu uncompressed audio music type directories(s) to go through music file renaming in directory $(pwd)"
	echo -e "************************************************************"
	if [ "$DEBUG" = "debug" ]
	then
		echo AUDIODIRCOUNTU=$AUDIODIRCOUNTU >> $DEBUGLOG
		echo countleft=$countleft >> $DEBUGLOG
		echo dircountu=$dircountu >> $DEBUGLOG
		echo totalcountleft=$totalcountleft >> $DEBUGLOG
		echo -e "\n************************************************************" >> $DEBUGLOG
		echo -e "\nthis run for uncompressed audio files" >> $DEBUGLOG
		echo "There are $AUDIODIRCOUNTU compressed audio files in $dircountu compressed audio music type directories(s) to go through music file renaming in directory $(pwd)" >> $DEBUGLOG
		echo -e "************************************************************" >> $DEBUGLOG
	fi
	echo -e "\n************************************************************" >> $RENAMELOG
	echo -e "\nthis run for uncompressed audio files" >> $RENAMELOG
	echo "There are $AUDIODIRCOUNTU uncompressed audio files in $dircountu compressed audio music type directories(s) to go through music file renaming in directory $(pwd)" >> $RENAMELOG
	echo -e "************************************************************" >> $RENAMELOG
	# file renaming starts here
	CNT=0
	for f in ${UNCOMPRESSEDFILESARRAY[*]}
	do
		CNT=$(( CNT + 1 ))
		AUDIOFILEEXT=${f##*.}
		if [ "$DEBUG" = "debug" ]
		then
			echo "renaming with command: filebot -rename $f --format \"{pi.pad(2)}.{t.space('_').replaceAll(/&/,\"and\").replaceAll(/#/,\"number\").replaceAll(\"[^a-zA-ZÀ-ÿ0-9_-]\", \"\")}\" --db $DBID  >> $DEBUGLOG" >> $DEBUGLOG
			filebot -rename $f --format "{pi.pad(2)}.{t.space('_').replaceAll(/&/,\"and\").replaceAll(/#/,\"number\").replaceAll(\"[^a-zA-ZÀ-ÿ0-9_-]\", \"\")}" --db $DBID >> $DEBUGLOG
			echo "the filename is = $f" >> $DEBUGLOG
		else
			filebot -rename $f --format "{pi.pad(2)}.{t.space('_').replaceAll(/&/,\"and\").replaceAll(/#/,\"number\").replaceAll(\"[^a-zA-ZÀ-ÿ0-9_-]\", \"\")}" --db $DBID  >> $RENAMELOG
		fi
		fcut=$(echo ${f##*/} | cut -c -30)
				printf "\r%b" "\033[2K"
		printf "%3d %% completed - %5d of %5d - %s" "$(($CNT*100/$AUDIODIRCOUNTU))" "$CNT" "$AUDIODIRCOUNTU" "$fcut"
		#echo -en "$(($CNT*100/$AUDIODIRCOUNTU))% completed - $CNT of $AUDIODIRCOUNTU - $fcut \r"
	done

Last edited by rwyarbrough; 10-31-2018 at 06:10 PM.
 
1 members found this post helpful.
Old 10-31-2018, 02:43 PM   #8
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: Somewhere in my head.
Distribution: Slackware (15 current), Slack15, Ubuntu studio, MX Linux, FreeBSD 13.1, WIn10
Posts: 10,342

Rep: Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242
Quote:
Originally Posted by rwyarbrough View Post
For the directory renaming, I use mediainfo https://mediaarea.net/en/MediaInfo - Multiplatform - quite a nice program. it has quite a few fields, but you can run it once and parse the desired fields.
example output


For the actual file renaming, I use filebot (which I think also uses mediainfo as a call)

pi.pad(2) = track number padded to 2 digits
t.space('_') = Track Name with spaces replaced by underscores (along with other replacements)
$media.OverallBitrateString = overall bite rate
media.overallBitrateString will return the kbps value of the digital recording unless its a variable bitrate digital recording which will return "null", so I replace null with the word variable.
thanks, looks interesting, I'll give it a look through when I get a chance.
 
Old 10-31-2018, 02:49 PM   #9
rwyarbrough
Member
 
Registered: Oct 2003
Location: Mesquite, Texas
Distribution: Slackware_x64 15.0 and slackware-current
Posts: 33

Original Poster
Rep: Reputation: 2
Quote:
Originally Posted by mina86 View Post
Your code does not handle case when DIRALBUM is not set so I’m assuming that it’s always set
There is a check earlier not shown in the code block where if DIRALBUM is null, then I abort and move to the next record as there is no sense doing anything else if I can't get the album name from the tags.

Quote:
Originally Posted by mina86 View Post
Code:
NEWDIRNAME=${DIRRELEASED:-DIRRECORDED}.$DIRALBUM.$DIRRATE
NEWDIRNAME=${NEWDIRNAME#.}  # remove leading dot if date is missing
NEWDIRNAME=${NEWDIRNAME%.}  # remove leading dot if bitrate is missing
Great stuff - that is what I was looking for. Your next code example however looks the leanest and meanest and is what I will undoubtedly use in place of all my if/else statements...

Quote:
Originally Posted by mina86 View Post
Code:
date=${DIRRELEASED:-$DIRRECORDED}
NEWDIRNAME=$date${date:+.}$DIRALBUM${DIRRATE:+.}$DIRRATE
THAT'S IT!! That is the solution - removing the leading dot was where I was having all of my problems. Didn't know how to handle that without some type of if/else statement. Thank you so much for that! Marking this as SOLVED based on this post.

Last edited by rwyarbrough; 11-01-2018 at 07:17 AM.
 
Old 10-31-2018, 03:12 PM   #10
rwyarbrough
Member
 
Registered: Oct 2003
Location: Mesquite, Texas
Distribution: Slackware_x64 15.0 and slackware-current
Posts: 33

Original Poster
Rep: Reputation: 2
Quote:
Originally Posted by ntubski View Post
I think you're missing the do done for the while loop actually.
More than likely I am - that was a copy/paste from a much larger code block


Quote:
Originally Posted by ntubski View Post
So if I understand correctly, you have 4 variables, and you want to join them together with dots in between, leaving out empty variables.
Exactly. My initial problem was having null values, but still printing the dots, so I'd end up with either a dot as the first character, or two dots in the filename (release.album..mp3 for example)

Thanks for you suggestions and comments. They were helpful.

Last edited by rwyarbrough; 11-01-2018 at 07:00 AM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
CASE/ESAC logs out automatically any user AMoNdj Linux - Software 6 05-10-2017 10:47 PM
[SOLVED] Can't get bash case statement to set variable Southern Gorilla Programming 19 01-05-2017 06:56 AM
automate case/esac bash script blason Programming 5 07-30-2016 10:10 PM
case esac in shell script vadirajcs Programming 16 08-10-2011 07:43 AM
i want to make a script with case.esac Alexander.s Linux - Newbie 3 12-14-2004 05:29 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:21 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration