Home > Back-end >  How can I extract files from multiple folders and rename according to folder name (bash)?
How can I extract files from multiple folders and rename according to folder name (bash)?

Time:07-26

I have a folder A, which has folders B1, B2,B3, etc. Each folder contains log.txt file. What i want to do (using bash) is extract all log.txt files to folder A and rename them as B1.txt, B2.txt, B3.txt, etc. How can i do this?

I tried the script below, but got error: dr = sys.argv[1] IndexError: list index out of range

import shutil import os import sys

dr = sys.argv[1]

for root, dirs, files in os.walk(dr): for file in files: if file == "log.txt": spl = root.split("/"); newname = spl[-1]; sup = ("/").join(spl[:-1]) shutil.move(root "/" file, sup "/" newname ".txt"); shutil.rmtree(root)

CodePudding user response:

Something like:

#!/bin/bash

cd A || exit 1
for i in B*/; do
    i=${i%/}
    [[ -f "$i"/log.txt ]] &&
    mv "$i"/log.txt "$i".txt
done

There's also B ([0-9])/ (instead of B*) to specifically match one or more digits in the directory name. Requires shopt -s extglob first.

CodePudding user response:

A for loop over B... directories should get it done
Assuming A directory is adjacent to B ...

test

# try run

for file in B{1,2,3}/*.txt; do
    echo $file A/${file%/*}.txt;
done

sample output

B1/log.txt A/B1.txt
B2/log.txt A/B2.txt
B3/log.txt A/B3.txt

run

# safe-run
# cp not mv, not lose your files

for file in B{1,2,3}/*.txt; do
    cp $file A/${file%/*}.txt;
done
  • Related