Guide | basename is a useful small tool on the command line that can remove directories and suffixes from a given file name. |
System environment
Centos 7
How to use the basename command
In the Centos7 system, the basename
command has been installed by default , and the command is included in the coreutils
installation package. basename
There are two syntaxes:
basename NAME [SUFFIX]
basename OPTION... NAME...
The last part of basename. You can also delete any ending suffix. This is a simple command, the most basic is to remove the directory in front of the file and print it out:
[root@localhost ~]# basename /etc/yum.repos.d/CentOS-Base.repo
CentOS-Base.repo
The basename command deletes all ending /
characters by default :
[root@localhost ~]# basename /usr/local/
local
[root@localhost ~]# basename /usr/local
local
By default, each output line ends with a newline character (\n). To end with NUL, use the -z (--zero) option.
[root@localhost ~]# basename -z /usr/local
local[root@localhost ~]#
basename accepts multiple files
The basename command can accept multiple names as parameters. You can use the -a (--multiple) option, and then use spaces to separate the file list. For example, to get the file names of /etc/passwd and /etc/shadow, you can run:
[root@localhost ~]# basename -a /etc/passwd /etc/shadow
passwd
shadow
Delete the specified ending suffix
To remove any ending suffix from the file name, pass the suffix as the second parameter:
[root@localhost ~]# basename /etc/hostname name
host
另一种方法:
[root@localhost ~]# basename -s name /etc/hostname
host
In the above example, specify the name as the suffix, you can see that only the /
back and name
front content is displayed in the output result .
Usually, this function is used to delete the file extension:
[root@localhost ~]# basename -s .conf /etc/httpd/conf/httpd.conf
httpd
或者
[root@localhost ~]# basename /etc/httpd/conf/httpd.conf .conf
httpd
The following example uses the -a option to specify multiple files, and the -s option to specify the suffix content:
[root@localhost ~]# basename -a -s .conf /etc/sysctl.conf /etc/httpd/conf/httpd.conf
sysctl
httpd
Another way to remove the trailing suffix is to specify the suffix using the -s (--suffix = SUFFIX) option. Shown in the example above.
Use case
The following example shows how to use the for loop, mv command, and basename command in a bash script to replace the file extension from ".jpg" to ".jpeg" by replacing the image file under the current directory:
[root@localhost test]# vim convert.sh
#!/bin/bash
for file in *.jpg
do
mv "$file" "$(basename $file .jpg).jpeg"
done
to sum up
basename is a command line utility that can remove directories and suffixes from a given file name. Linux should be learned like this