使用bash提取文件夹名称

时间:2014-12-14 17:35:44

标签: bash

我在文件夹中列出了一系列的mp3

/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

有没有办法可以使用sed来获取文件夹名称

DJ aaa
DJ 02
DJ Chemist

4 个答案:

答案 0 :(得分:1)

您还可以将参数展开子字符串提取一起用作“dirname / basename”的替代方法;以下是从数据文件中读取所有目录名称的快速示例:

#!/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

<强>输入

$ 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

<强>输出:

$ ./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

答案 1 :(得分:0)

basenamedirname结合使用:

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

为您提供DJ aaa

答案 2 :(得分:0)

通过sed:

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

通过awk:

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

通过grep:

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

通过剪切:

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

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

通过cuts

cuts -2 file

答案 3 :(得分:0)

您可以尝试如下。 \(\)将标记从DJ到/

之前的最后一个字符的模式
sed 's#.*\(DJ [[:alnum:]]\{1,\}\)/.*#\1#g'

结果

DJ aaa
DJ 02
DJ Chemist