【问题标题】:using bash to extract a folder name [duplicate]使用bash提取文件夹名称[重复]
【发布时间】:2014-12-14 17:35:44
【问题描述】:

我有一系列 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

【问题讨论】:

  • 非常感谢 Basilevs,正是我想要的

标签: bash


【解决方案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

【讨论】:

  • 如果您使用 bash 方式,另一种选择是使用 read 为您进行拆分:IFS=/ read -r -a line_ary; do ... 您将在 @987654326 中获得您想要的目录部分@.
  • 是的,我玩了很多方法。我喜欢-2 索引。那是我没有考虑过的。我在使用for 循环进行处理时设置了IFS,但原因完全相反。感谢您的评论。
【解决方案2】:

basenamedirname 结合起来:

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

给你DJ aaa

【讨论】:

  • 并且你仍然需要在echo语句中引用命令替换:echo "$(basename "$d")",否则你的代码会受到路径名扩展的影响。
【解决方案3】:

通过 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

【讨论】:

  • 在您的cut 解决方案中,您假设字段数量是固定的。这不好。
  • @gniourf_gniourf 是的,但我不想在那里使用rev 命令。但更新了:)
【解决方案4】:

您可以像下面这样尝试。 \(\) 将标记从 DJ 到 / 之前的最后一个字符的模式

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

结果

DJ aaa
DJ 02
DJ Chemist

【讨论】:

    猜你喜欢
    • 2012-03-25
    • 2016-01-25
    • 2019-11-11
    • 2010-09-18
    • 2020-08-29
    • 2017-10-02
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多