Linux

如何按文件副檔名將文件目錄拆分為命名的子目錄?

  • November 8, 2022

我有一個包含這些文件的目錄

2022-11-08-0001.gzip
2022-11-08-0002.gzip
2022-11-08-0003.txt
2022-11-08-0004.png
2022-11-08-0005.txt
2022-11-08-0006.txt
2022-11-08-0007.png
2022-11-08-0008.txt
2022-11-08-0009.txt
2022-11-08-0010.png

並想像這樣將它們拆分為子目錄

/gzip
2022-11-08-0001.gzip
2022-11-08-0002.gzip

/png
2022-11-08-0004.png
2022-11-08-0007.png
2022-11-08-0010.png

/txt
2022-11-08-0003.txt
2022-11-08-0005.txt
2022-11-08-0006.txt
2022-11-08-0008.txt
2022-11-08-0009.txt

我找到了這個簡短而甜蜜的解決方案,但由於文件副檔名的長度不同,我無法根據自己的需要對其進行自定義。但是,文件的基本名稱長度相同。

您只需遍歷每個文件名,如果匹配的目錄尚不存在,則創建匹配的目錄,然後將文件移動到那裡。就像是

#!/bin/bash
for filename in *; do
 # if filename is not a regular file, skip
 [ -f "${filename}" ] || continue

 # ${}: variable expansion
 # ${variable/pattern/replacement}: Pattern Replacement
 # pattern begins with #, meaning it must start at beginning of name
 # pattern is *., meaning "all up to the last dot"
 # replacement is empty
 suffix="${filename/#*./}"

 # skip files with no extension
 [ "${suffix}" = "${filename}" ] && continue

 # make that directory. Or ignore the fact it's already made.
 mkdir -p "${suffix}"
 mv "${filename}" "${suffix}"
done

使用zsh(並假設模式2022-*.*匹配所有相關文件,即名稱以字元串開頭2022-並包含至少一個點的文件):

for name in 2022-*.*; do
   mkdir -p $name:e && mv $name $name:e
done

zsh,$variable:e將與 相同$variable,但刪除最後一個點之前的所有內容(留下“副檔名”)。

測試:

$ tree
.
|-- 2022-11-08-0001.gzip
|-- 2022-11-08-0002.gzip
|-- 2022-11-08-0003.txt
|-- 2022-11-08-0004.png
|-- 2022-11-08-0005.txt
|-- 2022-11-08-0006.txt
|-- 2022-11-08-0007.png
|-- 2022-11-08-0008.txt
|-- 2022-11-08-0009.txt
`-- 2022-11-08-0010.png

0 directories, 10 files
$ for name in 2022-*.*; do mkdir -p $name:e && mv $name $name:e; done
$ tree
.
|-- gzip
|   |-- 2022-11-08-0001.gzip
|   `-- 2022-11-08-0002.gzip
|-- png
|   |-- 2022-11-08-0004.png
|   |-- 2022-11-08-0007.png
|   `-- 2022-11-08-0010.png
`-- txt
   |-- 2022-11-08-0003.txt
   |-- 2022-11-08-0005.txt
   |-- 2022-11-08-0006.txt
   |-- 2022-11-08-0008.txt
   `-- 2022-11-08-0009.txt

3 directories, 10 files

使用zshfrom (並在腳本中bash使用的縮寫形式,並將變數的名稱壓縮為):for``zsh -c``name``n

zsh -c 'for n; mkdir -p $n:e && mv $n $n:e' zsh 2022-*.*

引用自:https://unix.stackexchange.com/questions/724140