Wednesday, May 8, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 477  / 1 Year ago, fri, march 10, 2023, 5:21:43

I want to rename all files called Caudate_masks to lower case: caudate_masks.


In my directory I have several folders, one of them called Controls and other one called Patients. Inside each one of them you can find the Caudate_masks folders.


   Controls

└───C01
│ └─── Caudate_masks
│ └─── ...
└───C02
│ └─── Caudate_masks
│ └─── ...
└───C03
│ └─── Caudate_masks
│ └─── ...


Patients

└───H01
│ └─── Caudate_masks
│ └─── ...

This is what I have:


#!/bin/bash
DIR="/media/roy/Analysis"
for group in Controls Patients; do
cd $DIR/$group || exit
for folder in *; do
for cortical in "$folder/"*; do
if [ $cortical = "$folder/Caudate_masks" ]; then
mv $cortical caudate_masks
fi
done;
done;
done;

If I execute:


if [ $cortical = "$folder/Caudate_masks" ]; then
echo $cortical

I get a list of all the folders of interest, however, mv $cortical caudate_masks doesn´t change names, but move files, and rename doesn´t appear as a valid function.


More From » bash

 Answers
7

Install the rename package:


sudo apt install rename

Then it's a shell one-liner:


[sh @ balrog] ~/tmp 27 % tree
.
├── a
│   └── Caudate_masks
├── b
│   └── Caudate_masks
└── c
└── Caudate_masks

6 directories, 0 files

[sh @ balrog] ~/tmp 28 % rename 's/Caudate_masks/caudate_masks/' **/Caudate_masks

[sh @ balrog] ~/tmp 29 % tree
.
├── a
│   └── caudate_masks
├── b
│   └── caudate_masks
└── c
└── caudate_masks

6 directories, 0 files

Notice that modern shells (bash, zsh) support the ** wildcard which means "somewhere in this directory tree".




The reason why your script doesn't work as expected is that in this snippet


        for cortical in "$folder/"*; do
if [ $cortical = "$folder/Caudate_masks" ]; then
mv $cortical caudate_masks
fi
done;

your old name contains the directory (from $folder), yet the new name does not. It should work if you change that line to


                mv $cortical $folder/caudate_masks

[#1590] Saturday, March 11, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ticrew

Total Points: 190
Total Questions: 111
Total Answers: 99

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
ticrew questions
Mon, Jan 10, 22, 07:20, 2 Years ago
Wed, Dec 8, 21, 19:25, 2 Years ago
Wed, May 5, 21, 08:17, 3 Years ago
Fri, Nov 4, 22, 06:43, 2 Years ago
Sun, Jul 18, 21, 13:42, 3 Years ago
;