Basename Command in Linux

In Linux, the basename command prints the last element of a file path. This is especially useful in bash scripts where the file name needs to be extracted from a long file line.

The “basename” takes a filename and prints the filename’s last portion. It can also delete any following suffix if needed.

Let’s use different examples to understand the basename command in Linux.

Syntax:

It supports two syntaxes:

  • basename Path Suffix
  • basename option pathname

In the first syntax, add a suffix at the end of path/filename, and in the second, we can add an option. We cannot add an option with a suffix.

Using basename command with filename:

Create the file by using the touch command:

$ touch file_name

In this example, the file is named bash.txt:

$touch bash.txt

Now, let’s use the file with the basename command:

$ basename filepath

It will print the filename only.

Removing any / trailing character:

Use the following command to remove any trailing/character from the path:

$ basename file_path /

Remove trailing suffix:

Transfer the suffix as a second argument to delete any trailing suffix from the file name:

$ basename file_pathsuufix  suffix

Normally, this command is used to remove file extension:

Another way is to remove the trailing suffix from the file:

$ basename –s suffix filepathsuffix

Print or remove multiple files:

We can print or remove multiple file suffixes from files by using the -a flag. To print multiple filenames, use the following command:

$ basename –a filepath1 filepath2

We can also remove trailing suffixes from multiple files by using the below command:

$ basename –a –s suffix Filepath1_suffix  filepath2_suffix

Conclusion:

A basename is a command-line tool that removes the directory and suffix from assigned file names. The basename command print the last portion of the file name on the terminal. This post describes the basename command in detail.



from Linux Hint https://ift.tt/3cpfpXa

Post a Comment

0 Comments