Printable Version of Topic

Click here to view this topic in its original format

Linuxhelp _ Programming in Linux _ how do I grep a portion of the current directory?

Posted by: Grumps Mar 24 2014, 08:45 AM

I need to copy a portion of the current directory into a variable for use within a bash script.

Example:
typing pwd returns "/apps/dir1/subdir1/subdir2/subdir3/subdir4"

how do I use grep (assuming grep is the right tool?) to select only the 1st 2 directories of the path. i.e. how do I get it to return "/apps/dir1"

I've tried:
pwd | grep /w+\/{2}

and probably 100 other variations of the commands (incl. xargs), but they only ever return an error, or nothing whatsoever.

Same question if I wanted only the 1st directory of pwd: "/apps"
or up to the 3rd directory: "/apps/dir1/subdir1"
or ONLY the 3rd directory: "/subdir1"

Please help a guy who knows this should be easier than he's making it?

Thank you!

Posted by: michaelk Mar 24 2014, 05:16 PM

awk may work. Since it is using / as a field separator the output will be:
pwd = /dir1/dir2

pwd | awk 'BEGIN { FS = "/" } ; { print $2 }'

dir1

Posted by: Grumps Mar 25 2014, 07:58 AM

Thanks, michaelk, that helps!

It's returning just the directory name "dir1" or "dir2" etc. What I'd like to retrieve is "/dir1/subdir1" including the fwd-slashes.

I modified the awk you sent to:

pwd | awk 'BEGIN { FS = "/" };{ print "/"$2"/"$3"/" }'

so it would return "/dir1/dir2/" but I'd hoped to find a (grep/awk/sed) command with a regex that, basically, did ..."RETURN EVERYTHING BEFORE THE 3rd FWD-SLASH"
or the same but "INCLUDE THE 3rd /".... then, subsequently, "EVERYTHING BEFORE THE 4th /" etc...
Is this possible?

In the interim, I can use the awk you provided. Thank you, again!



QUOTE (michaelk @ Mar 24 2014, 05:16 PM) *
awk may work. Since it is using / as a field separator the output will be:
pwd = /dir1/dir2

pwd | awk 'BEGIN { FS = "/" } ; { print $2 }'

dir1


Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)