1

I am trying to extract, in linux (tcsh), the last part of a delimited string.

For example: I have a string that is /dir1/dir2/dir3 and the output should be only dir3.

The complete task I want to implement is: I want to find directory names that follow a given pattern, but "find"command returns a full path and not only the last directory, which is really what I want. Moreover, the result from the "find"command should be split into an arry to be processed later with a script.

command I am using to find the directory:

find path -maxdepth 2 -type d -name "*abc*"

Thanks in advance, Pedro

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • Possible duplicate of [How to only get file name with linux \`find\`?](https://stackoverflow.com/questions/5456120/how-to-only-get-file-name-with-linux-find) – kvantour May 15 '18 at 09:15

1 Answers1

1

You might be interested in the command basename :

$ basename /dir1/dir2/dir3
dir3

man basename : Print NAME with any leading directory components removed.

This can be combined with find as :

$ find path -maxdepth 2 -type d -name "*abc" -exec basename {} \;

or you can avoid basename and just pipe it to awk as :

$ find path -maxdepth 2 -type d -name "*abc" | awk -F'/' '{print $NF}'

But if you really want to avoid anything and just use find you can use the printf statement of find as :

$ find path -maxdepth 2 -type d -name "*abc" -printf "%f\n"

man find: %f File's name with any leading directories removed (only the last element).

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • Hi, Thanks for the reply, Output of find command: mydir1 mydir2 mydir3 I would like to add all of the results to a list/array, so I can use a for loop to iterate through the items. Best regards, Pdro – Pedro Cardoso May 15 '18 at 09:47