【问题标题】:Moving files to directories with similar names, in a script在脚本中将文件移动到具有相似名称的目录
【发布时间】:2012-02-07 12:05:02
【问题描述】:

我有一个目录,其中包含子目录和名称以类似于子目录的字符串开头的文件;例如

 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)。

【问题讨论】:

    标签: bash shell scripting


    【解决方案1】:

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

    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 用于使用参数扩展。如果我可以不使用ls,我会给你+2
    • 嘿,谢谢,@SiegeX。我喜欢花哨的 bash 参数扩展的东西,我花了 10 年的时间才达到可以使用它们而无需查找它们的地步(很多)。
    【解决方案2】:

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

    [ "$shvar" = "fox" ] 字符串比较,如果匹配则为真。

    【讨论】:

      【解决方案3】:

      [删除代码块]

      原因 1. 使用 ls 而不是通配符

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

      【讨论】:

      • 不要解析 ls,而是使用 glob。阅读this link 为什么不鼓励解析ls
      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多