0

If I have a file with lots of directory info like:

/home/svdev/src/lib
/home/dev/project/doc
/home/server/etc

I want to get the directory name next to "/home" directory. So for this set of data, my output should be svdev, dev, server

1
  • How is the data in the file, is it in one line, or one entry per line?
    – Jetchisel
    Mar 20, 2020 at 10:46

3 Answers 3

3
$ sed -e 's,^/home/,,' -e 's,/.*,,' file
svdev
dev
server

This uses sed to first delete the initial /home/ path, and then everything that comes after the first / in the remainder of the line.

I'm using commas as the delimiter to the s command in sed to avoid the leaning toothpick syndrome.

Another approach with sed is to replace the whole line with the second thing between /:

$ sed 's,/[^/]*/\([^/]*\)/.*,\1,' file
svdev
dev
server
1
  • @BISWAJITMAHARANA In a delete comment you mentioned that your actual data does not look as in the question. Could you please update your question with the actual data?
    – Kusalananda
    Mar 20, 2020 at 12:34
3

A very crude way of doing it using cut and specifying slash as delimiter:

cut -d "/" -f 3 thefile

Output:

svdev
dev
server

Assuming the directories all start with /home

1

if you want to print the sub-directories of /home

find /home -type d -maxdepth 1 -mindepth 1

if the paths are the content of a file,

awk -F '/' '{printf "%s, ",$3}' file.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .