2

I want to write a shell script so as to recursively list all different subdirectories which contain NEW subdirectory (NEW is a fixed name).

Dir1/Subdir1/Subsub1/NEW/1.jpg
Dir1/Subdir1/Subsub1/NEW/2.jpg
Dir1/Subdir1/Subsub2/NEW/3.jpg
Dir1/Subdir1/Subsub2/NEW/4.jpg
Dir1/Subdir2/Subsub3/NEW/5.jpg
Dir1/Subdir2/Subsub4/NEW/6.jpg

I want to get

Dir1/Subdir1/Subsub1
Dir1/Subdir1/Subsub2
Dir1/Subdir2/Subsub3 
Dir1/Subdir2/Subsub4

How can I do that?

3
  • Your question isn't very clear. For example, why do you not want to show Dir1/Subdir1/Subsub1/NEW? In any case do a man on find, which will likely do what you want... Commented Mar 9, 2018 at 17:08
  • Actually, I want to find all different addresses for my NEW subdirectories.
    – Mehdi
    Commented Mar 9, 2018 at 17:12
  • Yes, noticed your edit. You want to use find to find all directories named NEW, and then use sed to remove the trailing /NEWs... Commented Mar 9, 2018 at 17:13

3 Answers 3

2
find . -type d -name NEW | sed 's|/NEW$||'

--- EDIT ---

for your comment, sed does not have a -print0. There are various ways of doing this (most of which are wrong). One possible solution would be:

find . -type d -name NEW -print0 | \
  while IFS= read -rd '' subdirNew; do \
          subdir=$(sed 's|/NEW$||' <<< "$subdirNew"); \
          echo "$subdir"; \
  done

which should be tolerant of spaces and newlines in the filename

2
  • Thanks. But why is this code not working? find . -type d -name NEW | sed 's|/NEW$||' -print0 | while IFS= read -rd '' dir; do echo "$dir"; done
    – Mehdi
    Commented Mar 9, 2018 at 18:21
  • -print0 is an option to find, not sed. To use that with sed, you need to use sed -z. That's only supported in sed 4.2.2 and later. I'll edit my answer with a possible workaround Commented Mar 9, 2018 at 18:22
1

ls -R will list things recursively.

of find . | grep "/NEW/" should give you the type of list you are looking for.

1
  • HardcoreHenry's answer is probably more accurate. This approach only gives you the list of candidates, not the output list that is being asked for.
    – sgrover
    Commented Mar 9, 2018 at 17:17
1

You could try this:

find . -type d -name "NEW" -exec dirname {} \;

Not the answer you're looking for? Browse other questions tagged or ask your own question.