作業ディレクトリがあります。/home/myusername/projectdir
作業ディレクトリにはファイルとサブディレクトリが含まれています。サブディレクトリの深さが不明です。すべてのファイルを同じ出力ディレクトリに入れ、デフォルト名の前にサブディレクトリパス(で置き換え)を追加したいと
思います。*.log
/
#
例:
/home/myusername/projectdir/file1.log -> /home/myusername/output/file1.log
/home/myusername/projectdir/subdir/file2.log -> /home/myusername/output/#subdir#file2.log
/home/myusername/projectdir/subdir/subsubdir/file3.log -> /home/myusername/output/#subdir#subsubdir#file3.log
私はこれを試しました:
cd "$PROJECT_DIR"
CDIR=""
for x in **/*.log; do
if [ "$CDIR" != "$PROJECT_DIR/${x%/*}" ]; then
CDIR="$PROJECT_DIR/${x%/*}"
SUBDIR="${x%/*}"
PREFIX=${SUBDIR//'/'/'#'}
cd "$CDIR"
for FILENAME in *.log; do
NEWNAME="#$PREFIX#$FILENAME"
cp "$FILENAME" "$OUTPUT_DIR/$NEWNAME"
done
fi
done
どうすればよりエレガントにできますか?
ベストアンサー1
#!/bin/bash
newdir=/absolute/path/output
olddir=/absolute/path/project
find $olddir -name '*log' | while read line ; do
if [ "$olddir" == "$( basename "$line" )" ] ; then
#just move the file if there are no subdirectories
mv "$line" "$newdir"
else
#1) replace old project dir with nothing
#2) replace all slashes with hashes
#3) set new outdir as prefix
#4) hope that there are no colons in the filenames
prefix="$( sed -e "s:$olddir::" -e 's:/:#:g' -e "s:^:$newdir/:" <<<"$( dirname "$line")" )"
mv "$line" "$prefix"#"$( basename "$line" )"
fi
done