Skip to content
Advertisement

Using cut to remove until a delimiter from end

I have a string with many delimiters like :

abcd – efgh – foobar.extension (Delimiter ‘-‘)

I want to remove the

    - foobar.extension

So far, I have done

    a='abcd - efgh - foobar.extension'
    b=`echo $a | rev | cut -d'-' -f 1 | rev`
    echo $b

But this does not help as it echo’s

    foobar.extension

I want to be able to keep the inital part before the final delimiter(‘-‘) is found.

Advertisement

Answer

In bash you can use this built-in string manipulation:

a='abcd - efgh - foobar.extension'
echo "${a% -*}"
abcd - efgh

"${a% -*}" will remove any part of $a starting with a space followed by -, from end of the string.

Or using sed:

sed 's/ *- *[^-]*$//' <<< "$a"
abcd - efgh
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement