Question How to correctly remove first pattern match from string?

Status
Not open for further replies.

AlvinSeville

Prominent
Sep 7, 2020
13
0
520
Hello everyone! I have the task to remove first pattern match from string. Now my code is:
Bash:
#!/bin/bash

function removeFirstMatch()
{
  local string="$1"
  local pattern="$2"

  left=${string%%$pattern*}
  right=${string#*$pattern}

  echo "$left$right"
}

echo $(removeFirstMatch 'a\b\c' '\') # I want to obtain ab\c but actually get a\b\ca\b\c.
It works properly for cases without \ but I want it work normally everywhere.
 
No, no, they are not class work. They are just for my self-development. 😊 Sorry if they look like class work.

P.S. the solution for my question is:
Bash:
#!/bin/bash

function removeFirstMatch()
{
  local string="$1"
  local pattern="$2"

  left=${string%%"$pattern"*}
  right=${string#*"$pattern"}

  echo "$left$right"
}

echo $(removeFirstMatch 'a\b\c' '\')
 
Status
Not open for further replies.