Get the App
SLTechnology News&Howtos  ›  Servers  › 

The method of extracting File name and extension in Shell script

Shulou Source: shulou.com Published: 2022-06-02 04:35:33 10月04日 Update

How to extract file names and extensions in Shell scripts? This problem may be our daily study or work often see. I hope you learned something from this question. The following is the reference content brought to you by Xiaobian. Let's take a look together!

Sometimes you may need to extract file names and extensions from different variables to accomplish tasks in bash shell programming.

The following is the detailed content

1. Get the file name without path:

First delete the full file path from the input file name. For example, if the filename is entered as/etc/apache2/apache2.conf, only the full filename apache.conf.

#!/ bin/bashfullfilename="/etc/apache2/apache2.conf"filename=$(basename "$fullfilename")echo $filename

2. File names without extensions:

Now extract file names without extensions from the extracted full file names without paths, as shown below.

#!/ bin/bashfullfilename="/etc/apache2/apache2.conf"filename=$(basename "$fullfilename")fname="${filename%.*} "echo $fname

File extensions without names:

Now extract the file extension without name from the extracted full file name without path.

#!/ bin/bashfullfilename="/etc/apache2/apache2.conf"filename=$(basename "$fullfilename")ext="${filename##*.} "echo $ext

4. Testing:

Finally test everything in a shell script. Create a new script file using the following. The file name is passed as a command-line argument during script execution.

#!/ bin/bashfullfilename=$1filename=$(basename "$fullfilename")fname="${filename%.*} "ext="${filename##*.} "echo "Input File: $fullfilename"echo "Filename without Path: $filename"echo "Filename without Extension: $fname"echo "File Extension without Name: $ext"

We execute scripts with file names as command-line arguments.

$ ./ script.sh File: /etc/apache2/apache2.confFilename without Path: apache2.confFilename without Extension: apache2File Extension without Name: conf Thank you for reading! After reading this, do you have a general idea of how to extract filenames and extensions from Shell scripts? I hope the content of this article is helpful to everyone. If you want to know more about related articles, please pay attention to the industry information channel.

Tags: Files file names extensions contents scripts methods parameters names commands articles paths questions tests inputs differences tasks variables generals more see Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker vpn NVidia Huawei MariaDB