0

How can I copy directories from one location to another location that matches a pattern.

For example:

source = /media/src/
destination = /media/dest/
  • The pattern is as /b/w{2}_/w{2}/b. i.e all directories like aa_bb, fg_sd, re_ya, AA_BB, aa_Bx, Ba_BB etc.

2 Answers 2

2

You can use pattern matching:

cp /media/src/[[:lower:]][[:lower:]]_[[:lower:]][[:lower:]] /media/dest/

The [[:lower:]] is a POSIX defined character class which matches all characters classified as lowercase letters.

Edit: To match all characters use the character class alpha instead of lower:

cp /media/src/[[:alpha:]][[:alpha:]]_[[:alpha:]][[:alpha:]] /media/dest/
3
  • Sorry but it will just copy the directory with lower case, how about the directory name like aa_bb, fg_sd , re_ya, AA_BB , aa_Bx , Ba_BB
    – Nepal12
    Sep 8, 2015 at 8:59
  • @Nepal12 use alpha. see my edit
    – chaos
    Sep 8, 2015 at 9:02
  • Thanks it worked, btw can we do this using regular expression (just curious).
    – Nepal12
    Sep 8, 2015 at 9:17
0

Please check if this is what you wanted. It searches for directories with format xx_yy/ab_cd/&&_$$ (2char_2char) and copies the content to a new directory .

usage : ./script.sh

cat script.sh

#!/bin/bash

MYDIR="/media/src/"
NEWDIRPATH="/media/dest"
DIRS=`ls -l $MYDIR | grep "^d" | awk '{print $9}'`
for DIR in $DIRS
do
       total_characters=`echo $DIR | wc -m`
       if [ $total_characters -eq 6 ]; then
                has_underscore=`echo "$DIR" | grep "_"`
                if [ "$has_underscore" != "" ]; then
                        echo "${DIR}"
                        start_string_count=`echo $DIR | awk -F '_' '{print $1}' | wc -m`
                        end_string_count=`echo $DIR | awk -F '_' '{print $2}' | wc -m`
                        echo "start_string_count => $start_string_count ; end_string_count => $end_string_count"
                        if [ $start_string_count -eq 3 ] && [ $end_string_count -eq 3 ]; then

                                cp -r $DIR $NEWDIRPATH/
                        fi
                fi
        fi
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.