简体   繁体   中英

Send files to folders using bash script

I want to copy the functionality of a windows program called files2folder, which basically lets you right-click a bunch of files and send them to their own individual folders.

So

1.mkv 2.png 3.doc

gets put into directories called

1 2 3

I have got it to work using this script but it throws out errors sometimes while still accomplishing what I want

#!/bin/bash

ls > list.txt
sed -i '/list.txt/d' ./list.txt
sed 's/.$//;s/.$//;s/.$//;s/.$//' ./list.txt > list2.txt
for i in $(cat list2.txt); do
mkdir $i 
mv $i.* ./$i
done

rm *.txt

is there a better way of doing this? Thanks

EDIT: My script failed with real world filenames as they contained more than one. so I had to use a different sed command which makes it work. this is an example filename I'm working with

Captain.America.The.First.Avenger.2011.INTERNAL.2160p.UHD.BluRay.X265-IAMABLE

I guess you are getting errors on . and .. so change your call to ls to:

ls -A > list.txt

-A List all entries except for. and... Always set for the super-user.

You don't have to create a file to achieve the same result, just assign the output of your ls command to a variable. Doing something like this:

files=`ls -A`
for file in $files; do
  echo $file
done

You can also check if the resource is a file or directory like this:

files=`ls -A`
for res in $files; do
  if [[ -d $res ]];
  then
    echo "$res is a folder"
  fi
done

This script will do what you ask for:

files2folder :

#!/usr/bin/env sh

for file; do
  dir="${file%.*}"
  { ! [ -f "$file" ] || [ "$file" = "$dir" ]; } && continue
  echo mkdir -p -- "$dir"
  echo mv -n -- "$file" "$dir/"
done

Example directory/files structure:

ls -1 dir/*.jar
dir/paper-279.jar
dir/paper.jar

Running the script above:

chmod +x ./files2folder
./files2folder dir/*.jar

Output:

mkdir -p -- dir/paper-279
mv -n -- dir/paper-279.jar dir/paper-279/
mkdir -p -- dir/paper
mv -n -- dir/paper.jar dir/paper/

To make it actually create the directories and move the files, remove all echo

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