V
V
val182019-01-25 12:15:20
bash
val18, 2019-01-25 12:15:20

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

4 answer(s)
D
Dmitry Shitskov, 2019-01-25
@Zarom

Now you need to learn about commands that display a list of files in a column ls -1and a command that counts the number of lines wc -lin the process can be useful headeither tailto limit the number of output lines with file paths and xargsto pass parameters to mv
PS, it is probably better to use the -exec ls -1command insteadfind . -type f

P
pfg21, 2019-01-25
@pfg21

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

because ls gives additional lines in addition to listing files, the number will be greater than 1000

R
Roman Ratkin, 2019-01-25
@Hanharr

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

S
Saboteur, 2019-01-30
@saboteur_kiev

declare -i CNT=0
for FILE in dir1/*; do
  if ; then mv $FILE dir2; fi
  CNT+=1
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question