Unix cut except last two tokens

后端 未结 4 1360
执念已碎
执念已碎 2021-02-18 19:54

I\'m trying to parse file names in specific directory. Filenames are of format:

token1_token2_token3_token(N-1)_token(N).sh

I need to cut the t

相关标签:
4条回答
  • 2021-02-18 20:35

    It can not be done with cut, How ever you can use sed or awk

    sed -r 's/(_[^_]+){2}$//g'
    
    0 讨论(0)
  • 2021-02-18 20:36

    With cut:

    $ echo t1_t2_t3_tn1_tn2.sh | rev | cut -d_ -f3- | rev
    t1_t2_t3
    

    rev reverses each line. The 3- in -f3- means from the 3rd field to the end of the line (which is the beginning of the line through the third-to-last field in the unreversed text).

    0 讨论(0)
  • 2021-02-18 20:37

    Just a different way to write ysth's answer

    echo "t1_t2_t3_tn1_tn2.sh" |rev| cut -d"_" -f1,2 --complement | rev

    0 讨论(0)
  • 2021-02-18 20:51

    You may use POSIX defined parameter substitution:

    $ name="t1_t2_t3_tn1_tn2.sh"
    $ name=${name%_*_*}
    $ echo $name
    t1_t2_t3
    
    0 讨论(0)
提交回复
热议问题