Bash - 在移动到单个文件夹之前重命名带前缀的文件

时间:2017-08-16 11:27:48

标签: bash file-copying

使用bash如何找到扩展名为.txt的子目录中的所有文件,在名称前加上目录名?然后将所有这些.txt文件移动到当前目录中的单个文件夹中?

示例:

\subdirectory1\result1.txt  
\subdirectory1\result2.txt  
\subdirectory2\result1.txt  
\subdirectory2\result2.txt  
\subdirectory3\result1.txt  
\subdirectory3\result2.txt  

我想使用目录名复制和添加.txt文件,并将它们放在一个新目录中,结果是:

\newfolder\subdirectory1_result1.txt  
\newfolder\subdirectory1_result2.txt    
\newfolder\subdirectory2_result1.txt    
\newfolder\subdirectory2_result2.txt    
\newfolder\subdirectory3_result1.txt  
\newfolder\subdirectory3_result2.txt

3 个答案:

答案 0 :(得分:1)

鉴于您的源文件位于目录层次结构src中,并且您希望将其移动到目标目录target

for f in $(find src -type f -name \*.txt) # select all files in src
do
    d=$(dirname $f | sed 's/\//-/g')   # extract directory part of path and subsitute / with -
    mv "$f" target/"$d"-$(basename $f) # move to target dir
done

答案 1 :(得分:1)

find <subdirectory> -name "*.txt" | awk -v newfolder="somefolder" -F\/ '{ system("mv "$(NF-1)$NF" "newfolder) }'

使用awk,列出扩展名为txt的文件,然后使用“/”分隔的awk字段构建通过awk的系统函数执行的mv命令。传递的变量newfolder包含将文件移动到的路径。

使用这种awk解决方案注射存在风险,但它仍然是一种选择。

答案 2 :(得分:0)

使用find并与mv结合的非常简单的解决方案

find <currentDirToSearch> -name "*.txt" -exec mv {} <destinationDir> \;

例如

find . -name "*.txt" -exec mv {} dirToMove \;