简体   繁体   English

linux bash脚本创建文件夹和移动文件

[英]linux bash script to create folder and move files

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 my_file.jpg
create folder my_file 创建文件夹my_file
create folder picture 创建文件夹图片
move my_file.jpg to picture 将my_file.jpg移到图片上

I have this script but it only works on windows and now I'm using Linux 我有这个脚本,但它只适用于Windows,现在我正在使用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. 对不起,如果我不准确,但英语不是我的母语。

Use basename to create the directory name, mkdir to create the folder, and mv the file: 使用basename创建目录名,使用mkdir创建文件夹,然后使用mv文件:

for file in *.jpg; do
  folder=$(basename "$file" ".jpg")"/picture"
  mkdir -p "$folder" && mv "$file" "$folder"
done
#!/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

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. ${f%.jpg}.jpg之前提取文件名的一部分以创建目录。 Then the file is moved there. 然后文件移动到那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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