Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string on forward slash in bash

Tags:

example String :

/gasg/string

expected result : string

Characters to to remove: all characters between the "/" symbols including the symbols

like image 731
user1306777 Avatar asked May 27 '12 19:05

user1306777


People also ask

How do you split a string with a forward slash?

Use the str. split() method to split a string on the forward slashes, e.g. my_list = my_str. split('/') .

How do you split a variable in bash?

Method 1: Using IFS variable $IFS(Internal Field Separator) is a special shell variable. It is used to assign the delimiter(a sequence of one or more characters based on which we want to split the string). Any value or character like '\t', '\n', '-' etc. can be the delimiter.

How do you separate text in Linux?

To split a file into pieces, you simply use the split command. By default, the split command uses a very simple naming scheme. The file chunks will be named xaa, xab, xac, etc., and, presumably, if you break up a file that is sufficiently large, you might even get chunks named xza and xzz.


1 Answers

With sed:

$ echo "/gasg/string" | sed -e 's/\/.*\///g' string 

With buil-in bash string manipulation:

$ s="/gag/string" $ echo "${s##/*/}" string 

Your strings look exactly like Unix pathnames. That's why you could also use the basename utility - it returnes the last portion of the given Unix pathname:

$ basename "/gag/string" string # It works with relative paths and spaces too: $ basename "gag/fas das/string bla bla" string bla bla 
like image 157
Hristo Iliev Avatar answered Sep 30 '22 05:09

Hristo Iliev