我有大量目錄,其中包含數千個各種文件類型的文件:
dir
|__ subdir
| |__ file.foo
| |__ file.bar
| |__ file.txt
| |__ (...)
|__ (...)
從所有子目錄移動所有 .txt 的快速有效的方法是什麼有 2 行或更多行的文件到其他選定的目錄?
答案1
在 GNU 系統上:
find dir -type f -name '*.txt' -exec awk '
FNR == 2 {printf "%s\0", FILENAME; nextfile}' {} + |
xargs -r0 mv -t newdir
(請注意,這可能會導致同名檔案相互覆蓋。單次呼叫 GNUmv
可以防止這種情況,但如果xargs
呼叫多個,則可能會成為問題)。
答案2
shell / bash 是這樣的:
move_files_with_line_count()
(
srcdir="$1"
destdir="$2"
suffix="$3"
minlines="$4"
cd "$srcdir"
find . -name "*$suffix" -type f -print0 \
| while read -r -d $'\0' file; do
linecnt=$(wc -l "$file" | { read a b; echo $a; }; )
if [ $linecnt -ge $minlines ]; then
[ -d "$destdir/${file%/*}" ] \
|| echo mkdir -p "$destdir/${file%/*}"
echo mv -v "$file" "$destdir/$file"
fi
done
)
我用 () 包圍它,以便它恢復當前目錄。如果它按預期工作,請刪除“mkdir”和“mv”之前的“echo”。