【问题标题】:How can I make a bash script where I can move certain files to certain folders which are named based on a string in the files?如何制作一个 bash 脚本,在其中可以将某些文件移动到基​​于文件中的字符串命名的某些文件夹?
【发布时间】:2021-03-20 05:50:19
【问题描述】:

这是我用来将带有字符串“john”的文件(124334_john_rtx.mp4、3464r64_john_gty.mp4 等)移动到某个文件夹的脚本

find /home/peter/Videos -maxdepth 1 -type f -iname '*john' -print0 | \
xargs -0 --no-run-if-empty echo mv --target-directory=/home/peter/Videos/john/

由于我在文件中写入了大量具有各种名称的视频,因此我想制作一个 bash 脚本,将带有下划线之间的字符串的视频移动到基于下划线之间的字符串命名的文件夹中。因此,例如,如果文件名为 4345655_ben_rts.mp4,则脚本将识别下划线之间的字符串“ben”,创建一个名为下划线之间的字符串的文件夹,在本例中为“ben”,并将文件移动到该文件夹​​。非常感谢任何建议!

【问题讨论】:

  • 这个对不同问题的回答可能对您有所帮助:stackoverflow.com/a/64826172/3216427 它解决了从您的find 命令创建 bash 循环,您是否也需要帮助从文件名中提取子字符串?跨度>
  • 如果以下任一答案有帮助,请考虑接受最能解决您问题的答案。

标签: linux bash shell automation


【解决方案1】:

我的做法:

cd /home/peter/Videos # Change directory to your start directory
for name in $(ls *.mp4 | cut -d'_' -f2 | sort -u)  # loops on a list of names after the first underscore
do
    mkdir -p /home/peter/Videos/${name}  # create the target directory if it doesn't exist
    mv *_${name}_*.mp4 /home/peter/Videos/${name}  # Moving the files
done

【讨论】:

    【解决方案2】:

    这个 bash 循环应该可以满足您的需要:

    find dir -maxdepth 1 -type f -iname '*mp4' -print0 | while IFS= read -r -d '' file
    do
        if [[ $file =~ _([^_]+)_ ]]; then
            TARGET_DIR="/PARENTPATH/${BASH_REMATCH[1]}"
            mkdir -p "$TARGET_DIR"
            mv "$file" "$TARGET_DIR"
        fi
    done
    

    它只会在找到目录令牌时移动文件。

    我使用_([^_]+)_ 来确保目录名中没有_,但是如果文件名中的_ 超过两个,您没有指定您想要的内容。如果foo_bar_baz_buz.mp4 打算进入目录bar_baz,_(.+)_ 将起作用。

    这个对另一个问题的回答解释了find | while 逻辑:https://stackoverflow.com/a/64826172/3216427。

    编辑:根据 cmets 中的一个问题,我添加了 mkdir -p 来创建目标目录。 -p 表示递归创建路径中不存在的任何部分,如果完整目录已经存在,则不会出错。

    【讨论】:

    • 它有效,谢谢!但它只有在我使用该字符串之前创建文件夹时才有效。如何编辑 mv 行,以便创建一个名为 string 的新文件夹?我试着把 mkdir 放在那里,但没有用
    • @bennyblanco 您可以在mv 之前添加mkdir -p 语句,就像下面@Funkynene 的解决方案一样。我也会将其添加到我的答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2021-07-21
    • 2017-04-20
    相关资源
    最近更新 更多