Search code examples
bashcut

Cut the first and the last part of a string in bash


I have a string having this formats:

aa_bb_cc_dd
aa_bb_cc_dd_ee_ff

I want to obtain:

bb_cc
bb_cc_dd_ee

I've tried 'cut', but I didn't manage to obtain what I wanted.


Solution

  • when using bash you can use built-ins for this task:

    strip_headtail() {
     local s=$1
     ## strip the head
     s=${s#*_}
     ## strip the tail
     s=${s%_*}
    
     echo ${s}
    }
    
    strip_headtail aa_bb_cc_dd
    strip_headtail aa_bb_cc_dd_ee_ff
    

    you might want to check the bash-manual (man bash) for more information on this. search for Remove matching prefix pattern resp. Remove matching suffix pattern.