0

I want to get the tail from a given string which is generated by pwd command.
For example, if pwd command returns:

/home/example/src/github.com/abc/def  

And I want to get string from github.com to end.

github.com/abc/def 
0

5 Answers 5

2

You can use sed:

pwd | sed 's/.*github.com/github.com/'
Sign up to request clarification or add additional context in comments.

Comments

2

You can use parameter expansion in bash to achieve what you are looking for. Assuming you have the path as mentioned in PWD variable(same as output of $(pwd)), you can use the syntax {str##*} syntax to get the shortest string from the occurrence of the de-limiter to end of the string. In this case we use multi-character delimiter as github.com. Just do

printf 'github.com%s' "${PWD##*github.com}"

To store it in a new path just use the -v syntax provided by printf

printf -v newvar 'github.com%s' "${PWD##*github.com}"
printf '%s\n' "$newvar"
github.com/abc/def

or much simply use without printf just as

newvar="github.com${PWD##*github.com}"

Comments

1

Yet another solution, with grep:

pwd | grep -Eo 'github.com.*'

Basically: Take pwd and only print out the bit including and after github.com

Or, even if you're in a subdirectory of github.com/// and only want the two bits (author and repo name) after the github.com:

pwd | grep -Eo 'github.com/([^/]+/?){2}'

which pulls exactly 2 segments after the github.com

Comments

0

You can use sed to get the rest of the string and then combine it with 'github.com' using xargs to get the desired string:

pwd | sed 's/^.*github\.com//' | xargs -I {} echo "github.com{}"

Output:

github.com/abc/def

2 Comments

That's definitely an antipattern!
First step should be to get a solution that works. To optimize it should be next step.
0

If your goal is to start printing content with ANY directory segment that contains a period, you could do the following with awk:

$ awk 'BEGIN{ORS=RS="/"} /\./ {n=1} n' <<< "/home/example/src/github.com/abc/def"
github.com/abc/def

Of course, the same results could be achieved with sed

sed 's/.*[^a-z]\([a-z][a-z]*\..*\)/\1/'

Or grep alone:

egrep -o '[a-z]+\..*'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.