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: 變數內容的刪除、取代與替換


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...