Move files to directories based on first part of filename?

不羁的心 提交于 2019-12-02 23:21:24
for f in *.pdf; do
    name=`echo "$f"|sed 's/ -.*//'`
    letter=`echo "$name"|cut -c1`
    dir="DestinationDirectory/$letter/$name"
    mkdir -p "$dir"
    mv "$f" "$dir"
done

Actually found a different way of doing it, just thought I'd post this for others to see/use if they would like.

#!/bin/bash
dir="/books"
if [[ `ls | grep -c pdf` == 0 ]]
then
        echo "NO PDF FILES"
else
        for src in *.pdf
        do
                author=${src%%-*}
                authorlength=$((${#author}-1))
                letter=${author:0:1}
                author=${author:0:$authorlength}
                mkdir -p "$dir/$letter/$author"
                mv -u "$src" "$dir/$letter/$author"
        done
fi

@OP you can do it with just bash

dest="/tmp"
OFS=$IFS
IFS="-"
for f in *.pdf
do
    base=${f%.pdf}
    letter=${base:0:1}
    set -- $base
    fullname=$1
    pdfname=$2
    directory="$dest/$letter/$fullname"
    mkdir -p $directory
    cp "$f" $directory
done
IFS=$OFS
for i in *.pdf; do
  dir=$(echo "$i" | \
    sed 's/\(.\)\([^ ]\+\) \([^ ]\+\) - \(.*\)\.pdf/\1\/\1\2 \3/')
  dir="DestinationDirectory/$dir"
  mkdir -p -- "$dir" && mv -uv "$i" "$dir/$i"
done
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!