linux php basename,如何在Shell脚本中提取文件名和扩展名

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

ef41595a00c36a053fb0c5058ffa35fa.png

以下是详细的内容

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教程视频栏目!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值