2017-08-16 20 views
1

使用bash如何找到扩展名为.txt的子目录中的所有文件,以目录名称作为前缀名称?然后将所有这些.txt文件移动到当前目录中的一个文件夹中?Bash - 在移动到单个文件夹之前重命名具有前缀的文件

例子:

\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 
+0

添加实例以及 – syadav

回答

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 
+0

谢谢你一个非常简单的解决方案。这适用于单个命名文件夹。我做了一些改变,现在它完全符合我的想法。 '为我在*; do for f in $(find $ i -type f -name \ * .txt)#选择src中的所有文件 do d = $(dirname $ f | sed's/\ // -/g') #提取目录路径的一部分,并用# cp“$ f”target /“$ d” - $(basename $ f)#移动到目标目录 完成 完成# –

+0

@CarlKennedy我看,1.你有几个源目录(不只是一个)和2.你想复制,不移动。希望你找到我的答案有用,毫无疑问。 –

+0

我做了@KingThrushbeard,谢谢。 –

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

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

这个awk解决方案有注入风险,但它是一个选项。

0

使用查找和MV

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

例如结合

find . -name "*.txt" -exec mv {} dirToMove \; 
相关问题