Remove files with specific extensions by regexp
Emily Wong
I have Makefile for compiling LaTeX *.tex file (tex->dvi->ps->pdf). Then I have command clean for removing unnecessary temporary files (dvi, ps...) like this:
rm `ls | grep "^${FILENAME}\.(aux|dvi|ps|log)"`but it removes even the *.pdf file, that I need to keep.If I echo the result of the ls | grep, i found, it takes all files, whoose extension begins with the first letter of the extension in the regexp, so
echo `ls | grep "^${FILENAME}\.[aux|dvi|ps|log]"`
#echoes proj.aux proj.dvi proj.log proj.pdf proj.psOther files are left unchanged (*.tex)
How do I select only the files with extensions from regexp (and not *.pdf)? Thanks in advance.
13 Answers
On the command line, you should be using a shell glob instead of trying to regex-match the output of ls. For example, in bash you could use either a brace expansion
rm "$FILENAME".{aux,dvi,log,ps} or (if extended globbing is enabled)
rm "$FILENAME".!(tex|pdf)Within a Makefile, you should probably be using the make command's own text transformation functions - in the case of GNU make for example you could use addprefix e.g.
FILENAME = foo
.PHONY: clean
clean: @echo rm $(addprefix $(FILENAME),.aux .dvi .log .ps)giving
$ make clean
rm foo.aux foo.dvi foo.log foo.psSee GNU make: Functions for String Substitution and Analysis
First of all, don't use ls, use find. But anyway here is what you are looking for in the grep manpage:
Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below).so use something like this:
echo `find . | grep -E "^${FILENAME}\.(aux|dvi|ps|log)"` 2 This expression worked: ls | grep -E ".(aux|dvi|ps|log)". You did not use the -E flag, which allows for grep to use extended regular expressions (i.e. allows | to be interpreted as an or operator). Note: you could have also done ls | grep -E ".aux|dvi|ps|log" and gotten the desired outcome.