Find files containing string and rename

5

To find files whose name contains a certain string , we can use find as follows:

Sample file:

  

1429331804.H568641P9577.xxxx.example.com, S = 17846: 2,

Command to find by xxxx.example.com :

find . -type f -name "*xxxx.example.com*"

And this will only return the files containing the specified string .

Question

How to rename the returned files by replacing the key portion with another value?

  

1429331804.H568641P9577. xxxx.example.com , S = 17846: 2,

Go to:

  

1429331804.H568641P9577. yyyy.superbubu.pt , S = 17846: 2,

    
asked by anonymous 21.04.2015 / 23:21

3 answers

4

If you have or can install the program rename and all files are in the same directory:

rename 's/xxxx.example.com/yyyy.superbubu.pt/' *
    
22.04.2015 / 04:50
1

The @Clayton Stanley solution can be composed with find of the OP for situations where the files are in subdirectories:

find -type f -name "*xxxx.example.com*" \
             -exec rename 's/xxxx.example.com/yyyy.superbubu.pt/' {} \;

(sometimes the fantastic rename command (written by Larry Wall!) is available with the name prename)

    
22.04.2015 / 11:01
0

Here's a possible solution using bash script.

script.sh

#!/bin/bash

# Cria um arquivo texto com a lista de todos os resultados do find
# Cada linha eh um arquivo encontrado
find . -type f -name "*xxxx.example.com*" > lista.txt

# For-loop dentro do arquivo
while read p; do
    # O nome do arquivo origem eh a linha p
    ORIG=$p
    echo $ORIG

    # O nome do arquivo destino eh a linha p substituindo a URL
    DEST="$(echo $ORIG | sed s/xxxx.example.com/yyyy.superbubu.pt/)"
    echo $DEST

    # Copia o arquivo ORIG para DEST
    cp $ORIG $DEST
    # Altere cp para mv se voce tiver certeza que funciona
done <lista.txt

# Remove o arquivo lista.txt
rm lista.txt
    
22.04.2015 / 00:39