简体   繁体   中英

Move files into their own directories

I have several hundred rar files. I would like to create a directory for each rar file then move the file into the newly created directory.

This is the code I am using to create the rar's

#!bin/bash
for f in *; do 
rar a -s -m5 "${f%.*}.rar" "$f";
done

This is the code I am using to move the files.

#!/bin/bash
for i in *.rar; do
dir=$(echo "$i" | \
sed 's/\(.\)\([^ ]\+\) \([^ ]\+\) - \(.*\)\.pdf/\1\/\1\2 \3/')
dir="DestinationDirectory/$dir"
mkdir -p -- "$dir" && mv -uv "$i" "$dir/$i"
done

The problem is that it creates the directory with the extension name.

ie: file irclog3_26_198.rar is moved into folder /DestinationDirectory/irclog3_26_1988.rar/irclog3_26_1988.rar

I would like the folder to be created ignoring the .rar and just use the name of the file.

How about:

dir="${dir%.rar}"
mkdir -p -- "$dir" ...

Read more about it at the abs .

dir=$(echo ${i[@]::-4})

${name[@]:pos:len})获取字符串/数组的子字符串/子数组,对于字符串, [@]可以避免。

dir=$(echo ${i::-4})

You can use the normal bash shell parameter expension https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

FILE="TEST.rar"

echo "${FILE%%.*}"

--> TEST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM