Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing substring out of string using sed

I am trying to remove substring out of variable using sed like this:

PRINT_THIS="`echo "$fullpath" | sed 's/${rootpath}//' -`"

where

fullpath="/media/some path/dir/helloworld/src"
rootpath=/media/some path/dir

I want to echo just rest of the fullpath like this (i am using this on whole bunch of directories, so I need to store it in variables and do it automatically

echo "helloworld/src"

using variable it would be

echo "Directory: $PRINT_THIS"

Problem is, I can not get sed to remove the substring, what I am I doing wrong? Thanks

like image 275
rluks Avatar asked Mar 25 '12 14:03

rluks


2 Answers

You don't need sed for that, bash alone is enough:

$ fullpath="/media/some path/dir/helloworld/src"
$ rootpath="/media/some path/dir"
$ echo ${fullpath#${rootpath}}
/helloworld/src
$ echo ${fullpath#${rootpath}/}
helloworld/src
$ rootpath=unrelated
$ echo ${fullpath#${rootpath}/}
/media/some path/dir/helloworld/src

Check out the String manipulation documentation.

like image 157
Mat Avatar answered Nov 06 '22 23:11

Mat


To use variables in sed, you must use it like this :

sed "s@$variable@@g" FILE

two things :

  • I use double quotes (shell don't expand variables in single quotes)
  • I use another separator that doesn't conflict with the slashes in your paths

Ex:

$ rootpath="/media/some path/dir"
$ fullpath="/media/some path/dir/helloworld/src"
$ echo "$fullpath"
/media/some path/dir/helloworld/src
$ echo "$fullpath" | sed "s@$rootpath@@"
/helloworld/src
like image 10
Gilles Quenot Avatar answered Nov 07 '22 00:11

Gilles Quenot