在脚本中将文件移动到具有相似名称的目录

时间:2012-02-07 02:57:52

标签: bash shell scripting

我有一个目录,其子目录和名称以类似于子目录的字符串开头的文件; 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  

等。
所有文件目前都处于同一级别。我想将相应的.txt文件移动到带有脚本的类似名称的目录中(在我目前的情况下有> 9500)。

我写了以下内容,但我遗漏了一些东西,因为我无法移动文件。

#!/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

在我到达if之前,事情似乎正常。我正在研究一些* nix,所以我必须要小心我正在抛出什么样的论点(RHEL,FreeBSD,也可能是Mac OS X)。

3 个答案:

答案 0 :(得分:3)

假设您的文件与上面的模式非常匹配(最后一个破折号之前的所有内容都是目录名称),这应该这样做:

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

如果它告诉你命令行太长(将* .txt扩展到4900文件中很多)试试这个:

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

答案 1 :(得分:0)

我不是shell脚本专家,但我知道在很多shell中(根据互联网上的这个页面:http://www.vectorsite.net/tsshell.html这包括SH),字符串比较是用“=”运算符完成的,而不是“==”。

  

[“$ shvar”=“fox”]字符串比较,如果匹配则为true。

答案 2 :(得分:-1)

[删除了代码块]

原因1.使用ls代替globbing

原因2.使用mv $VAR1 $VAR2样式移动而不引用变量