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

Asked

Viewed 152 times

1

I’m 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 variable only the prefix eliminating the last part (e.g., the name "folder.test" or "things").

I tried with the cut and the grep but I could not take it back. N~]ao I was able to eliminate the last occurrence after the ".".

2 answers

2


Do not need to use any extra tool for this, because the bash is able to separate these words. Assign the filename 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 practical example with several files in the current directory:

#!/bin/bash

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

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

  • I had come here exactly to answer my own question rsrs... Man, thank you!

  • You’re welcome to have.

1

Usually in these situations it is useful to have prefix and suffix. By the way using a different approach:

ls -d *.*/ |                      ## get directorias contendo "."
sed -r 's!(.*)\.(.*)/!\1\n\2!' |  ## 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

Processing example: store directories as a function of suf -- replace "echo" with:

mkdir -p $e
mv "$p.$e" $e/$p
  • Man, very good! I tried to do in regex but could not, you killed the stick! Thanks!

  • Everton, thank you, I’m glad; yet it seems to me that @Fernandosilveira’s reply answers more directly to the question posed.

Browser other questions tagged

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