程式扎記: [Linux 常見問題] bash script: get just filename from path

標籤

2015年2月16日 星期一

[Linux 常見問題] bash script: get just filename from path

Source From Here
Question
How would I get just the filename without the extension and no path?

The following gives me no extension but I still have the path attached:
- test.sh
  1. #!/bin/sh  
  2. source_file="/abc/123/test.txt"  
  3. source_file_filename_no_ext=${source_file%.*}  
  4. echo "$source_file_filename_no_ext"  
Execution result:
$ ./test.sh
/abc/123/test

How-To
Most UNIXes have a basename executable for just that purpose (strips directory information and suffixes from filenames.); another similar executable is dirname(strips the last part of a given filename, in effect outputting just the directory components of the pathname.).

For example, we can rewrite test.sh this way:
  1. #!/bin/sh  
  2. source_file="/abc/123/test.txt"  
  3. source_file_filename_no_ext=${source_file%.*}  
  4.   
  5. echo "Input: $source_file"  
  6. source_file_filename_only=$(basename $source_file)  
  7. source_file_dirname_only=$(dirname $source_file)  
  8. source_file_filename_no_ext=${source_file_filename_only%.*}  
  9. echo "    Filename=$source_file_filename_only"  
  10. echo "    Dirname=$source_file_dirname_only"  
  11. echo "    Filename without extension=$source_file_filename_no_ext"  
Execution result:
$ ./test.sh
Input: /abc/123/test.txt
Filename=test.txt
Dirname=/abc/123
Filename without extension=test

Supplement
鳥哥 - 認識與學習 BASH: 變數內容的刪除、取代與替換


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!