-1

I've a series of mp3s set out in folders like so

/mnt/media/Music1/DJ_Mixes_01-71/DJ aaa/01.mp3
/mnt/media/Music1/DJ_Mixes_01-71/DJ 02/01.mp3
/mnt/media/Music1/DJ_Mixes_01-71/DJ Chemist/01.mp3

is there a way I can use sed to grab the folder names

DJ aaa
DJ 02
DJ Chemist
chemist
  • 153
  • 1
  • 8
  • 18
  • 1
    [See also](http://stackoverflow.com/questions/23162299/how-to-get-the-last-part-of-dirname-in-bash) – Basilevs Dec 14 '14 at 17:41

4 Answers4

1

You can also use parameter expansion with substring extraction as an alternative to `dirname/basename'; Here is a quick example reading all your directory names from a datafile:

#!/bin/bash

printf "\n The following directories were isolated:\n\n"

while read -r line || test -n "$line" ; do

    pname="${line%/*}"      # remove filename from line
    lastd="${pname##*/}"    # remove up to last '/'

    printf " %-12s  from  %s\n" "$lastd" "$line"

done <"$1"

printf "\n"

exit 0

input:

$ cat dat/mp3dirs.txt
/mnt/media/Music1/DJ_Mixes_01-71/DJ aaa/01.mp3
/mnt/media/Music1/DJ_Mixes_01-71/DJ 02/01.mp3
/mnt/media/Music1/DJ_Mixes_01-71/DJ Chemist/01.mp3

output:

$ ./lastdir.sh dat/mp3dirs.txt

 The following directories were isolated:

 DJ aaa        from  /mnt/media/Music1/DJ_Mixes_01-71/DJ aaa/01.mp3
 DJ 02         from  /mnt/media/Music1/DJ_Mixes_01-71/DJ 02/01.mp3
 DJ Chemist    from  /mnt/media/Music1/DJ_Mixes_01-71/DJ Chemist/01.mp3
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • If you're going the bash way, another option is to use `read` to do the splitting for you: `IFS=/ read -r -a line_ary; do ...` and you'll get the part of the directory you want in `line_ary[-2]`. – gniourf_gniourf Dec 14 '14 at 20:44
  • Yep, I played with a lot of ways. I like the `-2` index. That is one I did not consider. I had set `IFS` when using a `for` loop for processing, but for the completely opposite reason. Thanks for the comment. – David C. Rankin Dec 14 '14 at 22:22
0

Combine basename with dirname:

 f="/mnt/media/Music1/DJ_Mixes_01-71/DJ aaa/01.mp3"
 d=$(dirname "$f")
 echo "$(basename "$d")"

gives you DJ aaa

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • And you still need to quote the command substitution in the `echo` statement: `echo "$(basename "$d")"`, otherwise your code is subject to pathname expansion. – gniourf_gniourf Dec 14 '14 at 17:59
0

Through sed:

sed -r 's/.*\/(.*)\/.*$/\1/' file

Through awk:

awk -F/ '{print $(NF-1)}' file

Through grep:

grep -Po '.*\/\K.*(?=\/.*$)' file

Through cut:

cut -d'/' -f6 file            # for fixed number of fields 

or

rev file |cut -d'/' -f2 |rev  # for any length of fields  

Through cuts:

cuts -2 file
αғsнιη
  • 2,627
  • 2
  • 25
  • 38
0

You can try it like below. The \( and \) will mark the pattern from DJ to the last character before the /

sed 's#.*\(DJ [[:alnum:]]\{1,\}\)/.*#\1#g'

Results

DJ aaa
DJ 02
DJ Chemist
repzero
  • 8,254
  • 2
  • 18
  • 40