0

I have lots of files in a structure like this. There are .py files inside folder with the name std01...std60

/std01 (directory)
    problem1.py
    problem2.py
    problem3.py
/std02 (directory)
    problem1.py
    problem2.py
    problem3.py

By using bash commands, can I move and rename those files, so that it would be in a folder by the file name, leading by the std folder name?

/problem1.py (directory)
    std01_problem1.py
    std02_problem1.py
    ...
/problem2.py (directory)
    std01_problem2.py
    std02_problem2.py
    ...
srakrn
  • 352
  • 2
  • 16
  • Possible duplicate of [Batch renaming files with Bash](https://stackoverflow.com/questions/602706/batch-renaming-files-with-bash) – Wyatt Gillette Oct 09 '17 at 13:49

2 Answers2

3
for std in *; do
    for problem in "$std"/*; do
        problem=${std##*/}    # trim directory name
        mkdir -p "$problem"   # create dir if it doesn't already exist
        mv "$std/$problem" "$problem/$std_$problem"
    done

    rmdir "$std"   # if original directory is empty, remove it
 done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

find + bash solution:

Before:

$ tree std*
std01
├── problem1.py
├── problem2.py
└── problem3.py
std02
├── problem1.py
├── problem2.py
└── problem3.py

find . -type f -path "*std[0-9]*/problem[0-9]*.py" -exec bash -c \
'IFS=/ read -ra a <<<"$1"; mkdir -p "${a[-1]}"; mv "$1" "${a[-1]}/${a[-2]}_${a[-1]}"' _ {} \;

After:

$ tree problem*
problem1.py
├── std01_problem1.py
└── std02_problem1.py
problem2.py
├── std01_problem2.py
└── std02_problem2.py
problem3.py
├── std01_problem3.py
└── std02_problem3.py
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105