Shell script take out extension and search only by name

Asked

Viewed 356 times

1

Someone can fix my script?

The purpose of the script is to compare the input files with the files in the folder JUNK, the problem is that if the input file is teste1.txt he cannot find the file teste1.tar.bz2

#!/bin/bash

##CONSTANTES##

dir="/home/pasta/LIXO"

#check para ver se é file#
if ! [ -e $1 ]; then
        echo "Not a file!"
        exit 0
fi

###main###
#ciclo for para aceitar multiplas entradas de ficheiros##
for file in "$@"; do
#se o ficheiro de entrada existir no diretorio /LIXO#
if [[ -f $dir/$file ]]; then
        echo "|||File EXISTS|||"
#se o file de entrada for mais novo do que o file que lá está#
        if [[ $file -nt $2 ]]; then
                echo "file is newer"
        fi
else
echo "File doesnt exist, ziping it and moving"
fi
done


#to:do
#add tar / mv /rm
#eventualmente adicionar os comandos para fazer Zip do ficheiro e mover.
  • teste1.txt is the same thing as teste1.tr.bz2, thus the main objective is to compare "teste1" == "teste1" correct? Or still need to compress the file and move it?

  • at this moment yes! I will eventually add the commands to do Tar and move the file, the problem is that it does not find the zipped file!

1 answer

1

To remove the suffix .* of a variable just refer to it as ${variavel%%.*}. So you could fix your script and solve the problem:

#ciclo for para aceitar multiplas entradas de ficheiros##
for file in "$@"; do
    #se o ficheiro de entrada existir no diretorio /LIXO#
    fileprefix="${file%%.*}"
    if [[ -f "$dir/$fileprefix" ]]; then
        echo "|||File EXISTS|||"
        #se o file de entrada for mais novo do que o file que lá está#
        if [[ $file -nt $2 ]]; then
                echo "file is newer"
        fi
    else
        echo "File doesnt exist, ziping it and moving"
    fi
done

Browser other questions tagged

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