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
Execution result:
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:
Execution result:
Supplement
* 鳥哥 - 認識與學習 BASH: 變數內容的刪除、取代與替換
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
- #!/bin/sh
- source_file="/abc/123/test.txt"
- source_file_filename_no_ext=${source_file%.*}
- echo "$source_file_filename_no_ext"
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:
- #!/bin/sh
- source_file="/abc/123/test.txt"
- source_file_filename_no_ext=${source_file%.*}
- echo "Input: $source_file"
- source_file_filename_only=$(basename $source_file)
- source_file_dirname_only=$(dirname $source_file)
- source_file_filename_no_ext=${source_file_filename_only%.*}
- echo " Filename=$source_file_filename_only"
- echo " Dirname=$source_file_dirname_only"
- echo " Filename without extension=$source_file_filename_no_ext"
Supplement
* 鳥哥 - 認識與學習 BASH: 變數內容的刪除、取代與替換
沒有留言:
張貼留言