How to cut a suffix of an expression in bash (egrep / sed / etc)

1

I am making a script that works with directories that have suffixes defined and separated by ".", for example "folder.teste.git" or "things.var" and would like to take as a variable only the prefix eliminating the last one part (eg the name "folder.test" or "things").

I tried with the cut and the grep but I could not get it backwards. I was unable to delete the last occurrence after the ".".

    
asked by anonymous 04.08.2017 / 00:37

2 answers

2

You do not need to use any extra tools for this, since bash itself is able to separate these words. Assign the file name to a variable and use the % modifier:

nome_de_arquivo_completo="pasta.teste.git"
nome_de_arquivo_sem_extensao="${nome_de_arquivo_completo%.*}"
echo "${nome_de_arquivo_sem_extensao}"

Or, in a handy example with multiple files in the current directory:

#!/bin/bash

for filename in *; do
    echo "${filename%.*}"
done

What happens is that the % modifier removes a specified pattern from the end of a variable immediately afterwards ( .* , in this case).

    
04.08.2017 / 02:49
1

Normally in these situations it is useful to have prefix and suffix. Already using another different approach:

ls -d *.*/ |                      ## get directorias contendo "."
sed -r 's!(.*)\.(.*)/!\n!' |  ## separar prefixo suf.
while read p && read e            ## para cada par (prefixo, suf)
do  
   echo "Prefixo: $p" "suf: $e"   ## processar em função do prefixo, suf
done

Example of processing: sort the directories depending on the suff - replace the "echo" with:

mkdir -p $e
mv "$p.$e" $e/$p
    
04.08.2017 / 20:07