Find files containing string and rename

Asked

Viewed 586 times

5

To locate files whose name contains a particular string, we can resort to find as follows:

File example:

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

Command to locate by xxxx.example.com:

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

And this will return only the files that contain the string nominee.

Question

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

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

Passes to:

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

  • If you are writing a bash script you can put the name of the files in a variable and then use sed to change the filename using regular expressions. And then vc uses mv fich_orig fich_dest.

  • It is possible to use the find with the option exec, which runs a command with each result returned by find. See http://rberaldo.com.br/find-como-encontrararquivos-linux/

3 answers

4

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

rename 's/xxxx.example.com/yyyy.superbubu.pt/' *
  • Cool +1 (Name is actually part of my survival kit :)

1

The @Clayton Stanley solution can be composed with the 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 first name)

0

Here is 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

Browser other questions tagged

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