Bash Shell parsing path Get file name and folder name

Source: Internet
Author: User

Preface or Today write a self-starter packaging script. Used to get the last file name from the path name. Here is a record of the implementation process.

Of course, in the end I will also give the official approach. (PS: Very embarrassing, realized that the original bash Shell has a ready-made function)
Gets the file name if the given path name is:

/tmp/csdn/zhengyi/test/zhengyi.txt
The awk solution uses a "/" delimiter, and then prints out the last part.

Implementation code such as the following:

Resfile= ' Echo/tmp/csdn/zhengyi/test/adb.log | Awk-f "/" ' {Print $NF} '
The official solution (basename) Bash shell itself provides the basename command, which is able to get the name of the last file of the pathname directly, implementing the code such as the following:
Resfile= ' Basename/tmp/csdn/zhengyi/test/adb.log '

Get folder name official solution (dirname) The Bash shell itself provides the dirname command, which is particularly handy to get the path to the corresponding folder name, implementing code such as the following:
Dirpath= ' Dirname/tmp/csdn/zhengyi/test/adb.log '

The awk solution has the flexibility to use separators, which are mixed with the normal form:
Dirpath= ' Echo/tmp/csdn/zhengyi/test/adb.log | Awk-f '/[^/]*$ ' {print '} '

Awk+for Loop Method:
Echo/tmp/csdn/zhengyi/test/adb.log | awk ' begin{res= '; fs= "/";} {for (i=2;i<=nf-1;i++) res= (res "/" $i);} End{print Res} '


Bash Shell parsing path Get file name and folder name

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.