How to remove last element of the delimited string using Bash/Sed/Awk/Perl inside bash script

I have the following bash script


What I want to do is to remove last element of the $STR1 and $STR2 delimited with /, and do it inside that bash script.

Yielding in


for both $STR1 and $STR2 and assign it to a new variable say NW_STR1. How can I achieve that?

2 answers

  • answered 2018-11-08 05:48 RavinderSingh13

    Solution 1st: If you have GNU awk then try following.

    echo "$STR2" | awk 'BEGIN{FS=OFS="/"}NF--'

    Solution 2nd: Or with parameter expansion of pure BASH(probably BEST solution among all mentioned here).

    echo "${STR2%/*}"

    Solution 3rd: Using awk match.

    echo "$STR2" | awk 'match($0,/\/.*\//){print substr($0,RSTART,RLENGTH-1)}'

    Solution 4th: using sub of awk program.

    echo "$STR2" | awk '{sub(/\/[[:alnum:]]+$/,"")} 1'

  • answered 2018-11-08 05:51 Shawn

    Just use dirname:

    $ dirname /home/ubuntu/foo/hicpro_data/output/3333_XX501621_0368_AH2BHTBGX9/K4me3