Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash-在移动到单个文件夹之前使用前缀重命名文件_Bash_File Copying - Fatal编程技术网

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

Bash-在移动到单个文件夹之前使用前缀重命名文件,bash,file-copying,Bash,File Copying,使用bash如何查找扩展名为.txt的子目录中的所有文件,并在名称前加上目录名?然后将所有这些.txt文件移动到当前目录中的单个文件夹中 例如: \subdirectory1\result1.txt \subdirectory1\result2.txt \subdirectory2\result1.txt \subdirectory2\result2.txt \subdirectory3\result1.txt \subdirectory3\result2.txt 我想

使用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

假设源文件位于目录层次结构
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
find-name“*.txt”|awk-v newfolder=“somefolder”-F\/'{system(“mv”$(NF-1)$NF“newfolder”)}
使用awk,列出扩展名为txt的文件,然后使用以“/”分隔的awk字段构建通过awk的系统功能执行的mv命令。传递的变量newfolder包含将文件移动到的路径


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

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

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

同时添加示例,谢谢。这对于单个命名文件夹非常有效。我做了一些改变,现在它完全符合我的要求<代码>用于i in*;在$(find$i-type f-name\*.txt)中为f执行do#选择src do d=$(dirname$f | sed's/\/-/g')中的所有文件#提取路径的目录部分并用-cp“$f”target/“$d”-$(basename$f)替换/。您有多个源目录(不仅仅是一个)和2个。你想复制,而不是移动。希望我的回答对你有用,不是吗。
find <currentDirToSearch> -name "*.txt" -exec mv {} <destinationDir> \;
find . -name "*.txt" -exec mv {} dirToMove \;