-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? Commented 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
  • I have tried this already as TEST can be any word. so better to use parameter expansion method Commented May 28, 2020 at 18:10
  • @Rocky86 This has been fixed. See also unix.stackexchange.com/questions/169716 Commented May 28, 2020 at 18:26

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.