Extract filename and extension in Bash

后端 未结 30 1937
野趣味
野趣味 2020-11-21 05:29

I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo \"$FILE\" | cut -d\'.\'          


        
30条回答
  •  囚心锁ツ
    2020-11-21 06:09

    No need to bother with awk or sed or even perl for this simple task. There is a pure-Bash, os.path.splitext()-compatible solution which only uses parameter expansions.

    Reference Implementation

    Documentation of os.path.splitext(path):

    Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').

    Python code:

    root, ext = os.path.splitext(path)
    

    Bash Implementation

    Honoring leading periods

    root="${path%.*}"
    ext="${path#"$root"}"
    

    Ignoring leading periods

    root="${path#.}";root="${path%"$root"}${root%.*}"
    ext="${path#"$root"}"
    

    Tests

    Here are test cases for the Ignoring leading periods implementation, which should match the Python reference implementation on every input.

    |---------------|-----------|-------|
    |path           |root       |ext    |
    |---------------|-----------|-------|
    |' .txt'        |' '        |'.txt' |
    |' .txt.txt'    |' .txt'    |'.txt' |
    |' txt'         |' txt'     |''     |
    |'*.txt.txt'    |'*.txt'    |'.txt' |
    |'.cshrc'       |'.cshrc'   |''     |
    |'.txt'         |'.txt'     |''     |
    |'?.txt.txt'    |'?.txt'    |'.txt' |
    |'\n.txt.txt'   |'\n.txt'   |'.txt' |
    |'\t.txt.txt'   |'\t.txt'   |'.txt' |
    |'a b.txt.txt'  |'a b.txt'  |'.txt' |
    |'a*b.txt.txt'  |'a*b.txt'  |'.txt' |
    |'a?b.txt.txt'  |'a?b.txt'  |'.txt' |
    |'a\nb.txt.txt' |'a\nb.txt' |'.txt' |
    |'a\tb.txt.txt' |'a\tb.txt' |'.txt' |
    |'txt'          |'txt'      |''     |
    |'txt.pdf'      |'txt'      |'.pdf' |
    |'txt.tar.gz'   |'txt.tar'  |'.gz'  |
    |'txt.txt'      |'txt'      |'.txt' |
    |---------------|-----------|-------|
    

    Test Results

    All tests passed.

提交回复
热议问题