Help - Search - Members - Calendar
Full Version: how do I grep a portion of the current directory?
Linuxhelp > Support > Programming in Linux
Grumps
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!
michaelk
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
Grumps
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

This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2017 Invision Power Services, Inc.