Extracting directory name, filename and extension from the Shell script extraction path in Linux

Source: Internet
Author: User

When writing a script (Shell), you will often encounter the path name, file name, and so on in the filename including the full path.

This includes a full path file named

/usr/local/apach2/etc/httpd.conf

Defined as

File= "/usr/local/apach2/etc/httpd.conf"

(1) Extract filename

filename=${file##*/}

##*/represents the deletion from the front to the last/appearing part, so filename is httpd.conf.

(2) Extract the file name extension

ext=${file##*.}

As with (1), delete from the front to the last. Section, ext for CONF.

(3) Extraction of httpd

withoutext=${file%.*}

%.* deletes from the last start to the 1th time. The part of the without is/usr/local/apach2/etc/httpd.

(4) Extract directory name

dirname=${file%/*}

%/* deletes from the last start to the 1th occurrence/part, dirname for/USR/LOCAL/APACH2/ETC.

# #和 percent represents the longest consistent, while # and% indicate the shortest consistent. #表示从前面,% expressed from behind.

Here is a sample script

/tr>
  code is as follows copy code

#!/bin/ Bash

file= "/usr/local/apach2/etc/httpd.conf"

filename=${file##*/}
ext=${file##*.}
withoutext=${file%.*}
dirname=${file%/*}

Echo $FILENAME
Echo $EXT
Echo $WITHOUTEXT
Echo $ DirName

Execution results are

httpd.conf
conf
/usr/local/apach2/etc/httpd
/usr/local/apach2/etc

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.