Extract only the name of a file from the full path

1

I want to make a shell script that receives a filename with its full path, for example /home/42/arquivoEscolhido.txt , and extract only the file name ( arquivoEscolhido.txt ), which would be everything after the last slash ( / ), taking into account that the file name can always change.

I came up with something like this but it did not work:

echo -n 'Informe o arquivo: '

read dir       #/home/42/teste.txt

arq=${dir#*/}
    
asked by anonymous 30.11.2018 / 23:02

2 answers

3

Just missing one: arq=${dir##*/} will be teste.txt

${var#padrão} will remove only until the first occurrence of the pattern.

${var##padrão} will remove until the last occurrence of the pattern.

    
01.12.2018 / 00:19
1

Since this is a file path, another option is to use the basename command:

basename /home/42/teste.txt

The output is:

teste.txt

Inside a script, just run the command with command substitution syntax by placing it between $( ) :

echo -n 'Informe o arquivo: '

read dir       #/home/42/teste.txt

# executa o comando basename, a saída é colocada na variável arq
arq=$(basename $dir)

So, if the file path is /home/42/teste.txt , the variable arq will have the value teste.txt .

Bonus

According to documentation :

  

strip directory and suffix from filenames

Free translation:

  

remove directory and suffix of filenames

That is, you can also pass as a parameter the suffix to be removed. With this, you can also remove the file extension, for example:

basename /home/42/teste.txt .txt

Output:

teste
    
02.12.2018 / 01:39