CanOfBees
CanOfBees

Reputation: 93

Moving files to directories with similar names, in a script

I have a directory with sub-directories and files with names that start with a string similar to the sub-directories; e.g.

 bar/ 
     foo-1/ (dir)
     foo-1-001.txt
     foo-1-002.txt
     foo-1-003.txt
     foo-2/ (dir)
     foo-2-001.txt
     foo-2-002.txt
     foo-2-003.txt
     foo-3/ (dir)
     foo-3-001.txt
     foo-3-002.txt
     foo-3-003.txt  

etc.
All files are currently at the same level. I'd like to move the corresponding .txt files into their similarly-named directories with a script (there are > 9500 in my current situation).

I've written the following, but I'm missing something, as I can't get the files to move.

#!/bin/sh

# directory basename processing for derivatives
# create directory list in a text file
find ./ -type d > directoryList.txt


# setup while loop for moving text files around
FILE="directoryList.txt"
exec 3<&0
exec 0<$FILE
while read line
do
    echo "This is a directory:`basename $line`" 
filemoves=`find ./ -type f -name '*.txt' \! -name 'directoryList.txt' | sed 's|-[0-9]\{3\}\.txt$||g'`
if [ "`basename $filemoves`" == "$line" ]
    then
    cp $filemoves $line/    
    echo "copied $filemoves to $line"
fi  
done
exec 0<&3

Things seem to work OK until I get to the if. I'm working across a number of *nix, so I have to be careful what arguments I'm throwing around (RHEL, FreeBSD, and possibly Mac OS X, too).

Upvotes: 1

Views: 2023

Answers (3)

Keith Yoder
Keith Yoder

Reputation: 17

[code block removed]

Reason 1. Used ls instead of globbing

Reason 2. Used mv $VAR1 $VAR2 style moving without quoting variables

Upvotes: -1

Ry4an Brase
Ry4an Brase

Reputation: 78330

Assuming your files really match the pattern above (everything before the last dash is the directory name) this should do it:

for thefile in *.txt ; do mv -v $thefile ${thefile%-*}; done

and if it tells you command line too long (expanding *.txt into 4900 files is a lot) try this:

find . -name '*.txt' | while read thefile ; do mv -v $thefile ${thefile%-*} ; done

Upvotes: 3

mattbornski
mattbornski

Reputation: 12543

I'm not a shell script expert but I'm aware that in many shells (and according to this page on the internet: http://www.vectorsite.net/tsshell.html this includes SH), string comparison is done with the "=" operator, not "==".

[ "$shvar" = "fox" ] String comparison, true if match.

Upvotes: 0

Related Questions