2

I'm pretty new to the bash shell scripting game but have been catching on fairly well. I'm writing a script right now for the automated id3 data editing or mp3 files. I'm currently using the id3v2 command line program. These are mp3 files that are coming from a police scanner program I have recording. I'm wondering if there is a way to make a variable related to the number the file...you know I'm not sure how to word this. Sorry, been battling a headache for the last couple of days. I can explain it like this.

So if I were in a directory of recordings I can easily get them listed in order because the time they were recorded is a part of the file name. So a general ls command would produce something like

File_012030.mp3
File_012040.mp3
File_012045.mp3

I would like to use a variable to assign the track number to each files id3 data. My first thought is to somehow use the number of how far down it is in the list of files in that directory. So the above example would be.

File_012030.mp3 <- 01
File_012040.mp3 <- 02
File_012045.mp3 <- 03

Is this something that would be possible?

3

Just use a for loop and a counter:

k=1; for file in *mp3; do
        id3v2 --track "$k" "$file"
        ((k++))
     done

That will iterate over all files and directories whose name ends in mp3, saving each as $file. Then, the $k variable is incrementing once per iteration (((k++))) so $k will be the number of the file in the order you process them and you can use --track "$k" to set the track number.

  • Are there any characters to be concerned with in the *mp3 filenames? – MikeD Mar 25 '17 at 0:55
  • Okay I got it working...eventually. It took me a while to figure out what was wrong but eventually I got it. I'm not sure why but the dashes before "track" in your post...weren't the right kind of dashes? After playing around with the commands manually to see how it did and didn't work I noticed the dashes that were in the code you posted were longer when I straight copy and pasted "id3v2 −−track" as opposed to the - that showed up when I typed manually. It worked flawlessly. Now I'm reading up on that counter thing you used to see more about why this actually worked. Thanks – Jack black Mar 25 '17 at 1:07
1

It may be as simple as (works even with filenames that use newlines):

arr=(*)

All filenames in pwd will be stored in an array and accessed by its number, for example: "${arr[2]}".

The asterisk is very similar to ls, try echo * or, to select mp3's try echo *.mp3to see it in action.

You can view a list of all files with:

printf '%s\n' "${arr[@]}"

Then you may use a loop to process each filename:

for (( i=0 ; i<${#arr[@]} ; i++ )); do
    id3v2 --track "$((i+1))" "${arr[@]}"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.