BashScripts.org
http://bashscripts.org/forum/

script to obtain
http://bashscripts.org/forum/viewtopic.php?f=8&t=1198
Page 1 of 1

Author:  afflictedd2 [ Sat Sep 11, 2010 2:05 pm ]
Post subject:  script to obtain

Hi everyone,

How do I get the last 3 words of the path I'm currently in:
lets say I'm in

/home/john/part1/part2/part3

I want part1/part2/part3

Regards,

Ted

Author:  Patsie [ Sat Sep 11, 2010 2:45 pm ]
Post subject:  Re: script to obtain

The Sandbox
All Scripts go here. In progress, finished, etc.


Since I see no script, I assume you wanted to post your request in the request forum?

Author:  crouse [ Sat Sep 11, 2010 7:47 pm ]
Post subject:  Re: script to obtain

Patsie wrote:
The Sandbox
All Scripts go here. In progress, finished, etc.


Since I see no script, I assume you wanted to post your request in the request forum?



Good point... I moved it to the request forum.
Thanks Patsie.

Author:  crouse [ Sat Sep 11, 2010 8:04 pm ]
Post subject:  Re: script to obtain

It's ugly code... but hey, it's what you get when I spend a whole minute on a problem for you.
Think of it more as "food for thought" ;)
Code:
echo "/usr/local/bin/dave/test" | rev | awk -F"/" {'print $1"/"$2"/"$3'} | rev | grep -v "//"
bin/dave/test



also, look at basename.... you could do this better with basename ;)

Author:  Patsie [ Sun Sep 12, 2010 12:51 am ]
Post subject:  Re: script to obtain

I like the awk part, but feel it unnecessary to 'rev' it 2 times, so here's my solution:
Code:
echo "/home/john/part1/part2/part3" | awk -F/ '{print $(NF-2)"/"$(NF-1)"/"$NF}'


[edit]
Since 'basename' can only do the last part of a directory, I don't feel it viable for a better solution. The best I could come up with was:
Code:
var="/home/john/part1/part2/part3"
echo $(basename $(dirname $(dirname $var)))"/"$(basename $(dirname $var))"/"$(basename $var)
[/edit]

Author:  choroba [ Sun Sep 12, 2010 8:34 am ]
Post subject:  Re: script to obtain

Pure bash:
Code:
OLDIFS=$IFS
IFS='/'
steps=($PWD)
echo "${steps[*]: -3:3}"
IFS=$OLDIFS
:-B
You have not specified what should happen if the path has less than three components, though.

Author:  crouse [ Mon Sep 27, 2010 9:30 pm ]
Post subject:  Re: script to obtain

Patsie wrote:
I like the awk part, but feel it unnecessary to 'rev' it 2 times, so here's my solution:



he he he , I said it was UGLY code ;)

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com