-1

I have string(s) having delimiter underscore(_)

Input -

  1. ABC_TEST
  2. PQR_XYZ_TEST
  3. PQR_XYZ_ABC_TEST

Expected output -

  1. ABC
  2. PQR_XYZ
  3. PQR_XYZ_ABC

I want to remove only last part of the string. Can anyone suggest quicker way probably one-liner to achieve this?

1
  • 1
    Are the strings in a file?
    – Kusalananda
    May 28, 2020 at 18:24

2 Answers 2

2
string='ABC_TEST'
mod_string="${string%_*}"
echo "$mod_string"
ABC
1
1

The basic sed command is:

sed 's/_TEST$//' filename

or, to remove anything after the last _:

sed 's/_[^_]*$//' filename

If the strings come from another command: command | sed ...

If it's a variable sed ... <<< "${VARIABLE}"

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .