Recursively rename files to default given in Linux commands

Asked

Viewed 3,338 times

3

I am trying to rename files by making the default overwriting certain patterns, however, I wanted to do this work recursively and still could not get.

-/doc
|----- texto1.txt
|----- texto2.txt
|--/doc2
_|----- texto1.txt
_
|----- texto2.txt

Follows my

#!/bin/bash
#padrao = $1
#substitui = $2

ls | rename "s/$1/$2/g"

This script renames well what I want to modify, however only in the requested folder, I tried the "ls - R" however it did not work to do the substitution also in the internal folder(directories) the requested folder.

2 answers

6


Replaces ls with find, it will bring the list of files and sub-files. Something like:

find . -name "*.txt" | rename "s/$1/$2/g"

The dot brings the local directory, but you can even replace it with other directories, e.g.:

find /home/diretorio_de_usuario -name "*.txt" | rename "s/$1/$2/g"
  • Vlw, Lucas Polo. I checked here is just what I needed.

0

I made a script to rename screenshot files that appeared on the DESKTOP: image.sh

#!/bin/bash
cd ~/Desktop/
j=0
IFS="\n"
for i in `ls *.png`
do
  j=$(($j+1))
    if [ ! -e $1"$j".png ] ; then
      mv $i $1"$j".png
    else
    continue
    fi
done
cd -

How the script works?

  1. You run the script by providing an argument that will prefix the names.
    Ex: $ sh image.sh <prefixo> .

Out of command:

prefixo1.png, prefixo2.png, etc...

  1. The script is designed to list images .png, but this can be modified by placing it to be information passed by the command line with argument.

  2. If new images are inserted in the directory it will rename from the last stop.

I suggest you make some complementary script to apply the above code to each existing directory. It could be: $ find . -type d which will list all directories where you are from. The command xargs can be very useful to handle find output.

There are infinite possibilities!

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.