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

时间:2014-03-26 17:36:23

标签: linux bash shell

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

例如:
my_file.jpg
创建文件夹my_file
创建文件夹图片
将my_file.jpg移动到图片

我有这个脚本,但它只适用于Windows,现在我正在使用Linux

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

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

3 个答案:

答案 0 :(得分:3)

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

for file in *.jpg; do
  folder=$(basename "$file" ".jpg")"/picture"
  mkdir -p "$folder" && mv "$file" "$folder"
done

答案 1 :(得分:3)

#!/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

答案 2 :(得分:2)

尝试以下方法:

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

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