Answer the question
In order to leave comments, you need to log in
How to write a file transfer script in linux with a condition?
How to write a script with the condition: if there are more than 1000 files in folder 1, then move it in folder 1, leave 1000 files, and transfer the rest to folder 2?
So far, I only know these two commands for transferring files.
cd /home/user/export/bin
mv * /mnt/receipt/bin
Answer the question
In order to leave comments, you need to log in
Now you need to learn about commands that display a list of files in a column ls -1
and a command that counts the number of lines wc -l
in the process can be useful head
either tail
to limit the number of output lines with file paths and xargs
to pass parameters to mv
PS, it is probably better to use the -exec ls -1
command insteadfind . -type f
read the description
ls - listing files in a directory
wc - counting lines in a file
i.e. the script will be like this
if [$(ls /path/to/dir | wc -l ) > 10**]
then
mv ......
fi
If there are no files in the directory whose names begin with a period, then the oldest files will be moved offhand like this, leaving the last 1000 in the directory:
#!/usr/bin/env bash
DIR1="/path/to/dir1"
DIR2="/path/to/dir2"
i=0
for f in $DIR1; do
|| continue
_=$(( i++ ))
done
if $i -gt 1000; then
count=$($i - 1000)
files=$(find "$DIR1" -maxdepth 1 -type f -exec stat -c "%Y %n" {} \; | sort -rn | tail -n -"$count" | awk '{print $2}')
fi
for file in $files; do
mv "$file" $DIR2
done
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question