Linux Help
guides forums blogs
Home Desktops Distributions ISO Images Logos Newbies Reviews Software Support & Resources Linuxhelp Wiki

Welcome Guest ( Log In | Register )



Advanced DNS Management
New ZoneEdit. New Managment.

FREE DNS Is Back

Sign Up Now
> how do I grep a portion of the current directory?
Grumps
post Mar 24 2014, 08:45 AM
Post #1


Whats this Lie-nix Thing?
*

Group: Members
Posts: 2
Joined: 24-March 14
Member No.: 18,683



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!
Go to the top of the page
 
+Quote Post
 
Start new topic
Replies
michaelk
post Mar 24 2014, 05:16 PM
Post #2


Its GNU/Linuxhelp.net
*******

Group: Support Specialist
Posts: 1,797
Joined: 23-January 03
Member No.: 360



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
Go to the top of the page
 
+Quote Post
Grumps
post Mar 25 2014, 07:58 AM
Post #3


Whats this Lie-nix Thing?
*

Group: Members
Posts: 2
Joined: 24-March 14
Member No.: 18,683



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

Go to the top of the page
 
+Quote Post

Posts in this topic


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



RSS Lo-Fi Version Time is now: 18th October 2017 - 06:17 AM