Purpamine
Purpamine

Reputation: 141

Filename and File Globbing

I am trying to figure out a problem and this was very helpful Linux file names & file globbing but I am still having issues.

I have over a million files in my directory in my linux system. And I need to copy file with filename less than or equal to a certain number to another directory. For example:

cp all files with filename less than or equal to the number 29108273357520896 to another dir.

Can someone help me with this a little. The [][] thing is confusing me a lot.

Upvotes: 1

Views: 376

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84561

You can copy from dir1 to dir2 each file that exists between 0 - 29108273357520896 fairly easily:

#!/bin/bash

declare -i maxval=29108273357520896

function usage {

cat >&2 << TAG

Copy all files from 'srcdir' to 'tgtdir' with numeric names less than 'maxname'.

    Usage:  "${0//*\//}" srcdir tgtdir [maxname]  (maxname default: $maxval) 

TAG

    exit 1
}

## test required input
if [ -z "$1" -o -z "$2" ]; then
    printf "\n error: insufficient input.\n"
    usage
fi

## assign variables
srcdir="$1"
tgtdir="$2"
declare -i maxname="${3:-$maxval}"   # default maxval

## validate srcdir
if [ ! -d "$srcdir" ]; then
    printf "\n error: source dir does not exist.\n"
    usage
fi

## validate or create tgtdir
[ -d "$tgtdir" ] || mkdir -p "$tgtdir"
if [ ! -d "$tgtdir" ]; then
    printf "\n error: tgtdir does not exist and cannot be created, check permissions.\n"
    usage
fi

## validate maxname
if [ $maxname -gt $maxval ]; then
    printf "\n error: invalid 'maxname'. value exceeds maximum allowed: %s\n" "$maxval"
    usage
fi

## for 0 - $maxname, check that file exists, if so copy to tgtdir
for ((i=0; i<$maxname; i++)); do
    [ -f "$i" ] && cp -a "${srcdir}/${i}" "${tgtdir}"
done

exit 0

As a one-liner in the dir with the files

for ((i=0; i<29108273357520896; i++)); do [ -f "$i" ] && cp -a "$i" "/path/to/new/dir"; done

Upvotes: 1

Carlise
Carlise

Reputation: 126

Your question could use more context. Specifically, why do you have a million files? What is creating them? While you could use some shell scripting to work with this, there might be a more efficient way by not getting in this position in the first place.

Upvotes: 0

Related Questions