Home > front end >  bash sed replace from first ocurrence to right
bash sed replace from first ocurrence to right

Time:07-06

I am trying to obtain the first word before /

I am using following sed:

echo 'a/b/c' | sed 's/\(.*\)\/\(.*\)/\1/g'

But this gives me a/b, I would like it to give me only a

Any ideas?

CodePudding user response:

You can use

echo 'a/b/c' | sed 's,\([^/]*\)/.*,\1,'

Details:

  • \([^/]*\) - Group 1 (\1): any zero or more chars other than /
  • / - a / char
  • .* - the rest of the string.

Or, if you have a variable, you can use string manipulation:

s='a/b/c'
echo "${s%%/*}"
# => a

Here, %% removes the longest substring from the end, that matches the /* glob pattern, up to the first / in the string including it.

CodePudding user response:

This can be done easily in bash itself without calling any external utility:

s='a/b/c'
echo "${s%%/*}"

a

# or else
echo "${s/\/*}"

a

CodePudding user response:

Using sed and an alternate delimiter to prevent a conflict with a similar char in the data.

$ echo 'a/b/c' | sed 's#/.*##'
a

CodePudding user response:

Use cut instead of sed to isolate char-separated fields for clarity, simplicity, and efficiency:

$ echo 'a/b/c' | cut -d'/' -f1
a

$ echo 'a/b/c/d/e/f/g/h/i' | cut -d'/' -f5
e
  • Related