Mayday
Mayday

Reputation: 5136

bash sed replace from first ocurrence to right

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?

Upvotes: 1

Views: 38

Answers (4)

Ed Morton
Ed Morton

Reputation: 203169

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

Upvotes: 0

sseLtaH
sseLtaH

Reputation: 11207

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

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

Upvotes: 1

anubhava
anubhava

Reputation: 784918

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

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

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.

Upvotes: 1

Related Questions