Extract only the name of a file from the full path

Asked

Viewed 1,005 times

1

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

I came up with something like this but it didn’t work:

echo -n 'Informe o arquivo: '

read dir       #/home/42/teste.txt

arq=${dir#*/}

2 answers

4


Only one was missing #: 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.

  • Thank you so much! It Works!!

1

As it comes to the path of a file, another option is to use the command basename:

basename /home/42/teste.txt

The exit is:

teste.txt

Within a script, just run the command with the syntax of command substitution, putting him 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 the documentation:

strip directory and suffix from filenames

In free translation:

removes the file name directory and suffix

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

basename /home/42/teste.txt .txt

Exit:

teste

Browser other questions tagged

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