Home  >  Article  >  Operation and Maintenance  >  How to extract filename and extension in shell script

How to extract filename and extension in shell script

不言
不言Original
2019-03-19 15:50:3713224browse

有时你可能需要在不同的变量中提取文件名和扩展名来完成bash shell编程中的任务。本篇文章将介绍从完整的文件名或路径中提取文件名和文件扩展名。

How to extract filename and extension in shell script

以下是详细的内容

1、获取没有路径的文件名:

首先从输入文件名中删除完整的文件路径。例如,如果文件名输入为/etc/apache2/apache2.conf,则仅提取完整文件名为apache.conf.

#!/bin/bash

fullfilename="/etc/apache2/apache2.conf"
filename=$(basename "$fullfilename")
echo $filename

2、没有扩展名的文件名:

现在,从提取的不带路径的完整文件名中提取不带扩展名的文件名,如下所示。

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

3、没有名称的文件扩展名:

现在从提取的不带路径的完整文件名中提取不带名称的文件扩展名。

#!/bin/bash

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

4、测试:

最后在一个shell脚本中测试所有内容。使用以下内容创建新的脚本文件。在执行脚本期间,文件名将作为命令行参数传递。

#!/bin/bash

fullfilename=$1
filename=$(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"

我们以文件名作为命令行参数来执行脚本。

$ ./script.sh /etc/apache2/apache2.conf

Input File: /etc/apache2/apache2.conf
Filename without Path: apache2.conf
Filename without Extension: apache2
File Extension without Name: conf

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的Linux教程视频栏目!

The above is the detailed content of How to extract filename and extension in shell script. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn