简体   繁体   中英

How to rename text files within subfolders or zip files

I have multiple zip folders with unique names but the files within the folders all have the same name. I need to rename the text files to match the folder names. I also need those renamed text files to be moved to the working directory.

For example, I have the following:

name1.zip decompresses to name1\\AncestryDNA.txt but need to be name1.txt. name2.zip decompresses to name2\\AncestryDNA.txt but need to be name2.txt.

I used 7-Zip 19.00 to unzip the files. I decompressed the files because I also need to remove lines starting with "#" from each decompressed text file for use in another program.

I start with a windows batch file the runs the following on my Data directory that contains my zip files:

echo Unzipping the files...

forfiles /p Data /m *.zip /c "cmd /c 7z x *.zip -o* -y"

echo Moving zip files to storage...

forfiles /p Data /m *.zip /c "cmd /c move @file ..\StorageZipFiles"

echo Trimming all except header from AncestryDNA text files...

forfiles /p Data /s /m *.txt /c "cmd /c sed -i '/#/d' @file"

These work but I can't get the rename function to work.

I tried to rename the files before decompressing...

forfiles /p Data /s /m *.zip /c "cmd /c 7z rn @file @fname\AncestryDNA.txt @fname\@fname.txt" 

and...

forfiles /p Data /s /m *.zip /c "cmd /c 7z a rn @file @fname\AncestryDNA.txt @fname\@fname.txt"

and after decompressing...

forfiles /p Data /s /m *.txt /c "cmd /c ren @file @fname.txt" 

but I have not been successful with carrying the name of the folder over to the text file within the folder.

When trying to rename the files after decompressing, the command prompt does not produce an error message. It keeps the old file name of AncestryDNA.txt nested within the folders name1, name2, etc.

Another way of renaming the files after decompression is this powershell script.

Get-ChildItem  -recurse -path Data *.txt | rename-item -path {$_.fullname} -newname  {$($_ | split-path | split-path -leaf ) + ".txt"} -whatif

This has two interleaved powershell pipelines, one gets all the right directories and the second pipeline extracts the name of the folder used to rename the file. Note that I put a -whatif at the end of this for safety. If the output looks good then remove the -whatif to actually change the filenames. It is still best to test this on test data before using on real data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM