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

用于创建文件夹和移动文件的linux bash脚本,linux,bash,shell,Linux,Bash,Shell,您好,我需要根据文件名创建文件夹,在此文件夹中创建另一个文件夹,然后将文件移动到第二个文件夹 示例: my_file.jpg 创建文件夹“我的文件” 创建文件夹图片 将my_file.jpg移动到图片 我有这个脚本,但它只在windows上工作,现在我正在使用Linux for %%A in (*.jpg) do mkdir "%%~nA/picture" & move "%%A" "%%~nA/picture" pause 如果我不准确,很抱歉,但英语不是我的母语。使用basenam

您好,我需要根据文件名创建文件夹,在此文件夹中创建另一个文件夹,然后将文件移动到第二个文件夹

示例:
my_file.jpg
创建文件夹“我的文件”
创建文件夹图片
将my_file.jpg移动到图片

我有这个脚本,但它只在windows上工作,现在我正在使用Linux

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

如果我不准确,很抱歉,但英语不是我的母语。

使用
basename
创建目录名,
mkdir
创建文件夹,以及
mv
文件:

for file in *.jpg; do
  folder=$(basename "$file" ".jpg")"/picture"
  mkdir -p "$folder" && mv "$file" "$folder"
done
请尝试以下操作:

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

${f%.jpg}
提取
.jpg
之前的文件名部分以创建目录。然后将文件移到那里。

值得在
$f
sDon周围加上
“引号”
,你的意思是
basename“$file”“.jpg”
(先路径,然后后缀)?@mklement0谢谢。我真不敢相信我打了那个,结果也被否决了!:)这可能是由于~35k随附的重力。不打算去掉后缀(扩展名),例如
someFile.jpg
->
someFile
?语法是
basename-SUFFIX
(至少在Linux和OSX上是这样)。试试
basename“someFile.jpg.”jpg“
vs.
basename.jpg”someFile.jpg“
@mklement0,你关于重力的观点可能并不无效。在其他一些标签中,您需要在几秒钟内进行多次向上投票。(这些是图例,大约200k以上。
:)
)谢谢你,伙计,但是我需要把目标文件夹放在哪里,我的所有文件都在/root/Desktop/my_pictures中。我试图添加命令,该脚本应该在那里查看我的.jpg文件,但没有luckNicely完成;在这种情况下,
extglob
的一个更简单的替代方法是对*.jpg*.png*.gif中的文件使用
(尽管您需要处理不匹配的情况,例如使用
shopt-s nullglob
)。最好不要使用所有caps变量名,以避免与环境变量发生冲突-查看您的所有jpg文件当前位于/root/Desktop/My_pictures中?你希望他们在哪里?您想将参数传递给脚本还是在脚本中有目标?感谢您提供的提示mklement0是的,所有我的文件都在/root/Desktop/my_pictures中,我希望它们在那里,您可以在脚本中添加目标,例如图片“cat.jpg”/root/Desktop/my_pictures/cat/pictures/cat.jpg
#!/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