Nau
Nau

Reputation: 479

Script to Remove a Letter at the End of some Directories

Let's suppose I have a directory with this Structure:

enter image description here

I am making a script that removes the letter "x" in those cases when there is one at the end in order to have this:

enter image description here

So, I was thinking to do a For Loop that goes to each directory and then take the last part of the folder path

for d in Fruits_and_Vegetables/*/
do
     (cd "$d" && Fruit_or_Vegetable=`basename "$PWD"`)
done

The problem is that I am not sure how to tell to go and take only the last Directory

And then, I was thinking in modifying the string

echo $Fruit_or_Vegetable | awk '{print substr($1, 1, length($1)-1)}'  # substr(s, a, b) : it returns b number of chars from string s, starting at position a. 
                                                                      # The parameter b is optional, in which case it means up to the end of the string.

The problem is that I don't know how to tell AWK to consider "Moscato Giallox" as just one word, because when I execute the command it returns "Moscat Giallox" instead of "Moscato Giallo" .. also I guess I have to place an if statement to see if the last letter is x, and only execute the command in those cases.

Could you give me some suggestions, thanks.

Upvotes: 1

Views: 66

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15418

shopt and Parameter Expansion parsing can make that pretty easy. Starting with your directory structure above:

$: find @(Fruits|Vegetables)
Fruits
Fruits/Grapes
Fruits/Grapes/Muskat Grape
Fruits/Grapes/Muskat Grape/Muscat Ottonel
Fruits/Grapes/Muskat Grape/Muscato Gallox
Fruits/Mangoes
Fruits/Mangoes/Ataulfo Mango
Fruits/Mangoes/Tommy Atkins Mangox
Vegetables
Vegetables/Potatoes
Vegetables/Potatoes/Ratte Potatox
Vegetables/Potatoes/Yukon Gold Potato

Code for the changes you want.

shopt -s extglob  # allow fancy @(...) construct to specify dirs
shopt -s globstar # add double-asterisk for flexible depth
for d in @(Fruits|Vegetables)/**/*x/ # *EDITED* - added trailing / for dirs only
do echo "mv \"$d\" \"${d%x/}/\" "   # show the command first
         mv "$d" "${d%x/}/"         # rename the dirs
done

Output from the echo statements:

mv "Fruits/Grapes/Muskat Grape/Muscato Gallox/" "Fruits/Grapes/Muskat Grape/Muscato Gallo/"
mv "Fruits/Mangoes/Tommy Atkins Mangox/" "Fruits/Mangoes/Tommy Atkins Mango/"
mv "Vegetables/Potatoes/Ratte Potatox/" "Vegetables/Potatoes/Ratte Potato/"

Result:

$: find @(Fruits|Vegetables)
Fruits
Fruits/Grapes
Fruits/Grapes/Muskat Grape
Fruits/Grapes/Muskat Grape/Muscat Ottonel
Fruits/Grapes/Muskat Grape/Muscato Gallo
Fruits/Mangoes
Fruits/Mangoes/Ataulfo Mango
Fruits/Mangoes/Tommy Atkins Mango
Vegetables
Vegetables/Potatoes
Vegetables/Potatoes/Ratte Potato
Vegetables/Potatoes/Yukon Gold Potato

Upvotes: 2

Related Questions