cg_ext - script para alteração de extensão de arquivos em larga escala

Publicado por Tairan Andreo (última atualização em 28/02/2019)

[ Hits: 1.550 ]

Download cg_ext.sh




Script simples para realizar a troca de extensão de vários arquivos em um diretório. O programa está estável (pelos testes que realizei), mas aceito qualquer dica para a melhora do código ou para acrescentar novas funcionalidades.

Por padrão o script altera somente a extensão dos arquivos na pasta raiz informada e não nos seus subdiretórios. Caso necessário que a alteração também seja realizada para os subdiretórios (recursividade), a opção "-r" pode ser utilizada. Também existe a possibilidade de definir com mais precisão a profundidade máxima em relação ao nível que o script será aplicado nos diretórios. Essa funcionalidade é definida com a opção -maxdepth NUM, onde NUM deve ser um número inteiro não negativo.

Escrevi o script com meu inglês macarrônico mais como treino do que qualquer coisa, então se sentirem a necessidade posso alterar os comentários e a página de ajuda e deixar tudo em português.

Qualquer dúvida só chamar.

  



Esconder código-fonte

#!/bin/bash
#
# cg_ext.sh
# Author: Tairan Andreo
# Git: github.com/taandreo/
#
# This program is a script to change the file extension on a large scale.
#
# Version 1.0: Added support for options -V | --version and -h --help.
# Version 2.0: Added support for option -v | --verbose.
# Version 3.0: Added support for -i and -o options. 
# Version 4.0: Added support for -r and -maxdepth options. 

NAME=$(basename "$0")       # Program name

# Flags:

VERBOSE=0
MAX_DEPTH=1
RECURSIVE=0

HELP="Usage: $NAME [OPTIONS] -i .ext -o .ext2 DIRECTORY

OPTIONS:

    -i              Original extension.
    -o              Final extension.

    -h, --help      Print this help summary page.
    -V, --version   Print the version.
    -v              Enable Verbose.

    -maxdepth       Define de max depth.
    -r              Enable recursive mode.

EXAMPLES:
    
    $NAME -i .txt -o .csv .                Change the extension .txt to .csv for all files in this directory.
    $NAME -i .txt -o .csv . -v             Change the extension .txt to .csv all files in this directory and show each altered file.
    $NAME -i .txt -o .csv /home/user -r    Change the extension .txt to .csv for all files starting in /home/user and each subdirectory. 
"

is_ext(){
    # Create a regex which only matches 
    regex='^\.[[:alnum:]][.[:alnum:]]*'
    if !([[ "$1" =~ $regex ]])
    then
        echo "Invalid Argument: \"$1\"."
        echo "The argument must be a filename extension."
        exit 1
    fi
}

test_options(){
    if !(test -n "$1")
    then
        echo "-i option required."
    fi

    if !(test -n "$2")
    then
        echo "-o option required."
    fi

    if !(test -n "$3")
    then
        echo "Missing directory operand."
    fi
    
    if !(test -n "$1" & test -n "$2" & test -n "$3")
    then
        exit 1
    fi
}

if !(test -n "$1")
then 
    echo "$HELP"
    exit 0
fi

while test -n "$1"
do
    case "$1" in

        -h | --help)
            echo "$HELP"
            exit 0
        ;;

        -V | --version)
            echo -n $NAME
            egrep '^# Version' "$0" | tail -1 | cut -d : -f 1 | tr -d \# # Extract the version from the reader
            exit 0
        ;;
        
        -v)
            VERBOSE=1
        ;;
        
        -i)
            shift
            is_ext "$1" # Checks if the passed argument is a filename extension.  
            INPUT_EXT=$1
        ;;
        
        -o)
            shift
            is_ext "$1" # Checks if the passed argument is a filename extension.
            OUTPUT_EXT=$1
        ;;

        -maxdepth)
            shift
            MAX_DEPTH=$1
        ;;
        
        -r)
            RECURSIVE=1
        ;;
            

        *)  
            if test -d "$1"
            then
                DIRECTORY="$1"
            else
                echo "Invalid option: $1"
                exit 1
            fi
        ;;
    esac
    shift
done


test_options $INPUT_EXT $OUTPUT_EXT $DIRECTORY

if test $RECURSIVE = 1
then
    find  $DIRECTORY -regex "^.*\\$INPUT_EXT\$" > cache_find
else
    find  $DIRECTORY -maxdepth $MAX_DEPTH -regex "^.*\\$INPUT_EXT\$" > cache_find
fi

while read f
do
    if test $VERBOSE = 1
    then
        echo $f
    fi
    mv -- "$f" "${f%$INPUT_EXT}$OUTPUT_EXT"
done < cache_find

rm -f cache_find

Scripts recomendados

Firewall simples, com opções de redirecionamento

Firewall - FECHADO

pegando ip do windows update

Limpeza de Cache no Squid

Reativando Placa Wifi


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts