In a script I'd like to purge a mercurial repository but be able to retain a number of (configurable) file patterns which I read from $FILENAME. The syntax for the hg command is

hg purge --all --exclude PATTERN1 --exclude PATTERN2 ...

Thus if $FILENAME contains a list of file patterns (one pattern per line), each pattern must be prepended by an "--exclude " in order to construct the command line

My current approach is to use for construction of the argument list
grep -v -E "^[[:blank:]]*$" $FILENAME | sed "s/^/--exclude /g" | xargs echo
which also will skip empty lines and those which only contain tabs or spaces which would result in an error if used to construct the above command line. Thus in total:

hg purge --all `grep -v -E "^[[:blank:]]*$" $FILENAME | sed "s/^/--exclude /g" | xargs echo`

Is there a nicer way, maybe with some xargs arguments which I'm unaware of?

  • What does $FILENAME look like? Is it one pattern per line? – terdon Sep 23 '14 at 13:19
  • @terdon one file name per line – Faheem Mitha Sep 23 '14 at 13:20
  • 1
    simpler way : grep -v -E "^[[:blank:]]*$" $FILENAME | sed "s/^/--exclude /g" | xargs hg purge --all – Archemar Sep 23 '14 at 13:21
  • @terdon: yes indeed, my idea is to require one pattern per line in $FILENAME. I amended my question accordingly. – planetmaker Sep 23 '14 at 13:24

Seems there is even a shorthand way in mercurial itself, making use of file lists (suggested by mg in #mercurial):
hg purge --all --exclude "listfile:$FILENAME"


I don't understand why you're using grep and xargs at all. Given a file of patterns like this:


You could run

$ echo hg purge --all $(perl -pe 's/^/--exclude /' file)
hg purge --all --exclude foo --exclude bar --exclude baz

Or even

$ echo hg purge --all $(sed 's/^/--exclude /' file)
hg purge --all --exclude foo --exclude bar --exclude baz

Just remove the echo to actually run the commands.

  • Ah, that's indeed much nicer than my solution above. Thanks :) – planetmaker Sep 23 '14 at 13:50
  • @planetmaker you're welcome :). For future reference, the way to express thanks on the SE network of sites is to upvote answers you find useful and eventually accept one that solves your issue. – terdon Sep 23 '14 at 13:54
  • @planetmaker For reference, saying thanks is also fine.:-) In general people appreciate it. Also upvote as appropriate, of course. – Faheem Mitha Sep 25 '14 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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