[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] if exist

From: John McKown
Subject: Re: [Help-bash] if exist
Date: Sat, 13 May 2017 07:46:08 -0500

On Fri, May 12, 2017 at 8:21 PM, Val Krem <address@hidden> wrote:

> Hi all,
> I have list of files in a given folder  and some of these files are ending
> with any digit(starting from 1 up to may be  9 or more). My aim is if a
> file name is ending with any digit number then I want copy it to other
> folder and suppress the error message generated if the file does not exist
> in the folder.
> Sample of list of  files
> xbx1.txt1
> xby2.txt2
> xcx3.txt3
> xxx1.txt4
> xxy1.txt5
> Below is my attempt.
> #! /bin/bash
> dat0=/data/val1
> dat1=/data/val2
> shopt -s extglob
> cd ${dat0}
> xc=$(ls x*'.'txt{1..10})
> echo $xc
> for i in $(xc);do
>     if [  ${xc}  ];then
>        cp ${xc} $dat1
>     fi
> done
> But did not work.
> Can some one help me out?
​dat0=/data/va21 # "from" directory
dat1=/data/val2​ # "to" directory
find "${dat0}" -mindepth 1 -maxdepth 1 -type f -regexptype egrep -regex
'.*[0-9]$' | xargs -I {} cp -a {} "${dat1}"

Basically, "find" will do all work of finding the file names for you.
-mindepth 1 & -maxdepth 1 together says "only look for entries in _this_
directory (not in subdirectories)"
-type f means "only match regular files (not subdirectory names or symlinks
or ???)"
-regexptype egrep "use an extended regular expression"
-regex is the regular expression (extended per above) which is "any number
of characters followed by a trailing digit"

All of the files found will be fed into "xargs" which will construct a "cp"
command to do the actual work. Note that if there are a lot of file, this
may exceed the command buffer size. In that case, on the "xargs" command,
before the "-I' portion use "-n ..." switch to only copy ... files at a
time. xargs will split the files into groups that are ... entries long and
invoke "cp" as many times as necessary to get them all copies. E.g. if you
want to copy 10 at a time use:

... | xargs -n 10 -I {} cp -a {} "${dat1}"

Advertising is a valuable economic factor because it is the cheapest way of
selling goods, particularly if the goods are worthless. -- Sinclair Lewis

Maranatha! <><
John McKown

reply via email to

[Prev in Thread] Current Thread [Next in Thread]