3

I was writing a makefile and suppose I have the following;

FILES = file1.py \
    folder1/file2.py \
    folder2/file3.py

And I have the following for loop:

    -@for file in $(FILES); do \
           echo $${file/folder1\/}; \
    done

The above will print:

file1.py
file2.py
folder2/file3.py

The output I want is:

file1.py
file2.py
file3.py

I've looked at some documentation about shell expansion but couldn't yet find a way to deal with this. May I know how I should change the code to get the correct output? Any help will be very much appreciated.

EDIT: syntax

Jens
  • 69,818
  • 15
  • 125
  • 179
user945216
  • 251
  • 3
  • 14
  • Did you forget the backslashes in the `FILES =` lines? Did you forget the semicolon after the echo? – Jens May 07 '12 at 21:14
  • oh sorry, i forgot to add them in there, but I did write them in the makefile. Sorry for any confusion – user945216 May 07 '12 at 21:37

2 Answers2

5

You've already accepted @Jens's shell-style answer, but I'll suggest a make-style solution:

-@for file in $(notdir $(FILES)); do \
       echo $${file}; \
done
Beta
  • 96,650
  • 16
  • 149
  • 150
2

Try using echo $${file##*/}. This will give only the filename part without anything up to the last slash.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • Thank you so much! By the way, may I know where I can find the information related to this? I couldn't find any useful resources online. I don't think I should ask on StackExchange everytime I have a question like this.. – user945216 May 07 '12 at 21:36
  • 1
    It should be in your sh/ksh/bash/zsh manual under "Parameter Expansion". Note that `make` uses `/bin/sh` and not your login shell to run commands. `/bin/sh` might be a bash in disguise. The POSIX specs for parameter expansion are here http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 – Jens May 08 '12 at 07:25