-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?

Rocky86
  • 651

2 Answers2

2
string='ABC_TEST'
mod_string="${string%_*}"
echo "$mod_string"
ABC
Hauke Laging
  • 90,279
  • parameter expansion is nice, here's a link to some other PE tricks: http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion – b0yfriend May 28 '20 at 18:14
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}"

Kusalananda
  • 333,661
André Werlang
  • 268
  • 2
  • 11