linux bash script to create folder and move files

2019-07-22 02:49发布

Hello I need to create folder based on a filename and in this folder create another one and then move file to this second folder

example:
my_file.jpg
create folder my_file
create folder picture
move my_file.jpg to picture

I have this script but it only works on windows and now I'm using Linux

for %%A in (*.jpg) do mkdir "%%~nA/picture" & move "%%A" "%%~nA/picture"
pause

Sorry if I'm not precise but English is not my native language.

标签: linux bash shell
3条回答
一纸荒年 Trace。
2楼-- · 2019-07-22 03:06

Try the following:

for f in *.jpg; do
    mkdir -p "${f%.jpg}/picture"
    mv "$f" "${f%.jpg}/picture"
done

${f%.jpg} extracts the part of the filename before the .jpg to create the directory. Then the file is moved there.

查看更多
闹够了就滚
3楼-- · 2019-07-22 03:11

Use basename to create the directory name, mkdir to create the folder, and mv the file:

for file in *.jpg; do
  folder=$(basename "$file" ".jpg")"/picture"
  mkdir -p "$folder" && mv "$file" "$folder"
done
查看更多
倾城 Initia
4楼-- · 2019-07-22 03:22
#!/usr/bin/env bash

# Enable bash built-in extglob to ease file matching.
shopt -s extglob
# To deal with the case where nothing matches. (courtesy of  mklement0)
shopt -s nullglob

# A pattern to match files with specific file extensions.
# Example for matching additional file types.
#match="*+(jpg|.png|.gif)"
match="*+(.jpg)"

# By default use the current working directory.
src="${1:-.}"
dest="${2:-/root/Desktop/My_pictures/}"

# Pass an argument to this script to name the subdirectory
# something other than picture.
subdirectory="${3:-picture}"

# For each file matched
for file in "${src}"/$match
do
  # make a directory with the same name without file extension
  # and a subdirectory.
  targetdir="${dest}/$(basename "${file%.*}")/${subdirectory}"
  # Remove echo command after the script outputs fit your use case. 
  echo mkdir -p "${targetdir}"
  # Move the file to the subdirectory.
  echo mv "$file" "${targetdir}"
done
查看更多
登录 后发表回答