私は与えられたディレクトリ構造を平坦化できるシェルスクリプトを探していますが、ディレクトリにサブフォルダが1つしかない場合にのみ可能です。例:このスクリプトはこのフォルダを平坦化します。
/folder
/subfolder
file1
file2
入力する:
/folder
file1
file2
ただし、このフォルダはスキップされます(何もしません)。
/folder
/subfolder1
/subfolder2
よろしくお願いします。
スティーブ
ベストアンサー1
やや素朴なアプローチ:
#!/bin/sh
for dir do
# get list of directories under the directory $dir
set -- "$dir"/*/
# if there are more than one, continue with the next directory
# also continue if we didn't match anything useful
if [ "$#" -gt 1 ] || [ ! -d "$1" ]; then
continue
fi
# the pathname of the subdirectory is now in $1
# move everything from beneath the subdirectory to $dir
# (this will skip hidden files)
mv "$1"/* "$dir"
# remove the subdirectory
# (this will fail if there were hidden files)
rmdir "$1"
done
使用bash
:
#!/bin/bash
for dir do
# get list of directories under the directory $dir
subdirs=( "$dir"/*/ )
# if there are more than one, continue with the next directory
# also continue if we didn't match anything useful
if [ "${#subdirs[@]}" -gt 1 ] || [ ! -d "${subdirs[0]}" ]; then
continue
fi
# the pathname of the subdirectory is now in ${subdirs[0]}
# move everything from beneath the subdirectory to $dir
# (this will skip hidden files)
mv "{subdirs[0]}"/* "$dir"
# remove the subdirectory
# (this will fail if there were hidden files)
rmdir "${subdirs[0]}"
done
どちらのスクリプトも次のように実行されます。
$ ./script.sh dir1 dir2 dir3
または
$ ./script.sh */
現在のディレクトリのすべてのディレクトリで実行します。
コードの警告に加えて、シンボリックリンクを再接続できません。これを行うには、ファイルシステム内のすべての可能な場所に移動/folder
し、サブサブディレクトリへのリンクを見つけて正しい新しい場所を指すようにそのリンクを再作成する必要があります。ここでは、コードについてあまり深く取り上げません。
また、サブディレクトリからコンテンツを移動するときに同じ名前のエントリが下に存在しないことを確認するチェックはありません/folder
。