11

I searched all over for this, but the terms are apparently too general. I'm writing a script to search a group of folders for .mp3 files. Some folders don't have mp3's so they have to be excluded.

I created an array to hold the uniq'd folder names. This find command will get the folders I need.

Folders=$(sudo find /my/music/ -type f -name "*.mp3" | cut -d'/' -f7 | sort -u)

When I try to count the number of folders in the array, I always get 1

echo ${#Folders[@]}

echo ${Folders[@]} prints them out on separate lines so I thought they were separate array elements. Can anyone explain what is going on? You might have to jiggle the field number in the cut command to reproduce locally.

3
  • 2
    Where did you create the array? Folders=$(...) does not create an array... Commented Jul 26, 2016 at 19:03
  • If your path can contain whitespace or glob characters then creating array using command substitution isn't safe. Commented Jul 26, 2016 at 19:13
  • @twalberg - thanks! That was my 1st misunderstanding. And I know better too! Commented Jul 27, 2016 at 12:44

3 Answers 3

17

Folders is not an array but a variable.

You need:

Folders=( $(sudo find /my/music/ -type f -name "*.mp3" | cut -d'/' -f7 | sort -u) )

i.e. enclose the command substitution with (). Now ${#Folders[@]} would give you the number of elements of array Folders.

Sign up to request clarification or add additional context in comments.

Comments

0

Or do :

sudo find /my/music/ -type f -name "*.mp3" | cut -d'/' -f7 | sort -u | wc -l

Note

  • wc -l prints the number of lines which in this case would be the number of unique files
  • to make things a bit more explicit, use -printf "%p\n" option with find where %p specifier prints the file with full path.

Comments

0

Assuming bash 4 or later, don't use find here; use the globstar operator.

shopt -s globstar
folders=( /my/music/**/*.mp3 )

Also assuming that cut -d/ -f7 is supposed to extract the filename alone, follow this up with

folders=${folders[@]##*/}

Other methods for populating the array must take more care to accomodate files containing whitespace or characters like ?, *, or [. File names containing newlines (rare, but not illegal) are much more difficult to handle correctly. Pathname expansion is done inside the shell, so you don't need to worry about any such special characters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.