It looks like the other answers are assuming that you have multiple lines of data in a file, which are all to be processed. In this case sed
or awk
(or possibly cut
) would be the best tools for processing all the lines in one go.
However, if you just have one line in a shell variable (assuming you're using bash
), you can use shell expansions to achieve the desired result, without having to spawn utilities in external processes:
$ var="interesting/bla/blablabal/important"
$
$ # everything after the first slash:
$ echo "${var#*/}"
bla/blablabal/important
$ # everything after the last slash:
$ echo "${var##*/}"
important
$ # everything before the first slash:
$ echo "${var%%/*}"
interesting
$ # everything before the last slash:
$ echo "${var%/*}"
interesting/bla/blablabal
$
Alternatively, I assume your slash-separated strings are file paths. If that is the case, you can use dirname
and basename
to get the path and filename components:
$ # everything before the last slash:
$ dirname "$var"
interesting/bla/blablabal
$ # everything after the last slash:
$ basename "$var"
important
$
$
in the regex.cut -d/ -f2- <infile
cut
was designed for this job (extracting one or more fields) whilesed
is a "general purpose tool" (so not optimized for this task) ; also, regex is expensive: if you had to process millions of records with hundreds of fields each you'd see the difference...