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

How to extract filename and extension in shell script

不言
Release: 2019-03-19 15:50:37
Original
13379 people have browsed it

有时你可能需要在不同的变量中提取文件名和扩展名来完成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
Copy after login

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

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

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

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

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

#!/bin/bash

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

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"
Copy after login

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

$ ./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
Copy after login

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template