基于文本文件重命名多个文件夹名称

2024-10-01 04:48:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据我将提供的文本列表重命名特定路径中的文件夹名称。 例如,我有如下文件夹列表结构:

 /home/XXX-01/$file1
 /home/XXX-12/$file2
 /home/XXX-23/$file66
 /home/XXX-32/$file44
 /home/XXX-123/$file65

和rand.txt文件,详细说明需要更改的文件夹名称,例如

XXX-22
XXX-33
XXX-55
XXX-4321
XXX-24456

最终的文件夹结构如下

 /home/XXX-22/$file1
 /home/XXX-33/$file2
 /home/XXX-55/$file66
 /home/XXX-4321/$file44
 /home/XXX-24456/$file65

多谢各位


Tags: 文本路径文件夹名称home列表结构file1
1条回答
网友
1楼 · 发布于 2024-10-01 04:48:48

使用GNU awk版本4.0.2

 awk 'NR==FNR { # Process the list of directories (direcs.txt)
                map[NR]=$0 # Create an array indexed by the number record and with the directory as the value
              } 
      NR!=FNR { # Process the output of the find command
                
                newpath=gensub("(/home/)(.*)(/.*$)","\\1"map[NR]"\\3",$0); # Create the new path using the entry in the map array
                newdir=gensub("(/home/)(.*)(/.*.txt$)","\\1"map[num],$0) # Create the directory to create.
                print "mkdir "newdir # Print the mkdir command
                print "mv "$0" "newpath # Print the command to execute
              }' direcs.txt <(find /home -regextype posix-extended -regex "^.*[[:digit:]]+.*$")

一艘班轮:

 awk 'NR==FNR {map[NR]=$0} NR!=FNR { newpath=gensub("(/home/)(.*)(/.*.txt$)","\\1"map[NR]"\\3",$0);newdir=gensub("(/home/)(.*)(/.*.txt$)","\\1"map[num],$0);print "mkdir "newdir;print "mv "$0" "newpath }' direcs.txt <(find /home -regextype posix-extended -regex "^.*[[:digit:]]+.*$")

一旦您对命令的外观感到满意,就可以通过管道传输到bash/sh等来执行

 awk 'NR==FNR {map[NR]=$0} NR!=FNR { newpath=gensub("(/home/)(.*)(/.*.txt$)","\\1"map[NR]"\\3",$0);newdir=gensub("(/home/)(.*)(/.*.txt$)","\\1"map[num],$0);print "mkdir "newdir;print "mv "$0" "newpath }' direcs.txt <(find /home/robbo -regextype posix-extended -regex "^.*[[:digit:]]+.*$") | bash

相关问题 更多 >