2012-02-07 64 views
1

我有一个子目录和名称以类似于子目录的字符串开头的文件的目录;例如在脚本中将文件移动到具有相似名称的目录

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

假设文件确实符合上述模式(在最后一个短划线之前的所有内容都是目录名称)应该这样做:

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

+1使用参数扩展。我会给你+2,如果我可以也不使用'ls' – SiegeX 2012-02-07 03:41:05

+0

Ry4an - 非常感谢。 – CanOfBees 2012-02-07 12:34:16

+0

嘿,谢谢@SiegeX。我喜欢花哨的bash参数扩展的东西,并且我花了10年的时间来找到我可以使用它们的地方,而不用去查看它们(很多)。 – 2012-02-07 14:20:12

0

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

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

-1

[代码块移除]

原因1.用于ls代替通配符

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

+0

不解析'ls',使用水珠来代替。阅读[此链接](http://mywiki.wooledge.org/ParsingLs)为什么解析'ls'极不鼓励 – SiegeX 2012-02-07 03:40:16

相关问题