kwagjj
kwagjj

Reputation: 807

why is this sed command not working?

I want to strip some part of parent directories from result of pwd command. For a first step, I wanted to get the string part after 'home' with sed but I honestly don't know what I'm doing wrong. I think I've properly set the substring to be made and to be the output of sed substitute.

$ pwd
/home/user1/projects/bashscript
$ pwd | sed -r 's/\*home(\*)/\1/'
/home/user1/projects/bashscript

Upvotes: 1

Views: 752

Answers (2)

anubhava
anubhava

Reputation: 786291

Correct regex for sed is:

pwd | sed -r 's/.*home(.*)/\1/'

* can match anything in shell i.e. glob pattern but in regex equivalent pattern is .*.

However if you're using bash there is no need to use sed. You can do it using bash string manipulation:

echo "${PWD/\/home/}"

Update: Based on Ed's comment below if there are multiple /home in PWD.

Assuming PWD=/foo/123/home/dir/home/abcd:

it is more correct to use:

echo "${PWD#*/home}"
/dir/home/abcd
  • # will find a glob pattern from left (start) of the string
  • */home will remove everything until first occurrence of /home in value of PWD from left

Upvotes: 5

Avinash Raj
Avinash Raj

Reputation: 174874

You need to use .* (matches any character zero or more times) instead of \* . * is a special character in regex which repeats the previous token zero or more times. Dot in regex matches any character except line breaks.

$ pwd | sed -r 's~.*/home/(.*)~\1~'

OR

$ pwd | sed -r 's~.*/home(/.*)~\1~'

Use a different regex delimiter other than forward slash because your input contains forward slashes. Sometimes it may cause a mesh.

Upvotes: 3

Related Questions