A simple way to get file names and directory names using the bash shell _linux Shell

Source: Internet
Author: User

Objective
or do you write an automated packaging script today that takes you 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 practice. (PS: Very awkward, only to realize that the bash shell has ready-made functions)

Get file name
Suppose the given path name is:

 /tmp/csdn/zhengyi/test/zhengyi.txt 

awk Solution
use "/" to make the separator, and then print out the last part. The implementation code is as follows:

 Resfile= ' Echo/tmp/csdn/zhengyi/test/adb.log | Awk-f "/" ' {Print $NF} ' 

Official solution (basename)
the Bash shell itself provides the basename command to get the last filename of the pathname directly, implementing the following code:

 Resfile= ' Basename/tmp/csdn/zhengyi/test/adb.log ' 


Get directory Name
Official solution (DirName)
the Bash shell itself provides the dirname command, which is particularly handy for obtaining directory names corresponding to the path, implementing the following code:

 Dirpath= ' Dirname/tmp/csdn/zhengyi/test/adb.log ' 


awk Solution
You can use delimiters flexibly and mix regular expressions:

 Dirpath= ' Echo/tmp/csdn/zhengyi/test/adb.log | Awk-f '/[^/]*$ ' ' {print '} ' 


Methods of awk+for Circulation:

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

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.