Xorron

Q: How do I mask out files with a particular extension when using ls

How do I mask out files with a particular extension when using ls.

 

ie

 

ls "mask out .cmd"

 

Thanks

MacBook Pro with Retina display, OS X El Capitan (10.11.1), null

Posted on Sep 2, 2016 11:01 PM

Close

Q: How do I mask out files with a particular extension when using ls

  • All replies
  • Helpful answers

  • by VikingOSX,

    VikingOSX VikingOSX Sep 3, 2016 3:11 AM in response to Xorron
    Level 7 (20,544 points)
    Mac OS X
    Sep 3, 2016 3:11 AM in response to Xorron

    You enable/disable extglob in the Bash shell. Type the blue content in the Terminal.

     

    # enable extglob

    $ shopt -s extglob

    # show all files except those with .cmd extension. The '!' is a negation operator here.

    $ ls !(*.cmd)

    # disable extglob

    $ shopt -u extglob

     

    For more information on extglob, and additional operators, see man bash(1), and then search for extglob. Also, read this stackoverflow post on usage and other extglob operators.

  • by BobHarris,

    BobHarris BobHarris Sep 3, 2016 3:49 AM in response to Xorron
    Level 6 (19,257 points)
    Mac OS X
    Sep 3, 2016 3:49 AM in response to Xorron

    A very common method used by many Unix users is

     

    ls | grep -v '\.cmd$'

     

    This can be expanded to

     

    ls | grep -v '\.cmd$' | grep -v '\.fred$' | grep -v '\.another$' | etc...

     

    or

     

    ls | egrep -v '\.cmd$|\.fred$|\.george$|\.charlie$|\.paul$'

  • by Mark Jalbert,

    Mark Jalbert Mark Jalbert Sep 3, 2016 5:05 AM in response to Xorron
    Level 5 (4,649 points)
    Sep 3, 2016 5:05 AM in response to Xorron

    In bash as VikingOSX  points out ( note: added the d option to ls):

     

    shopt -s extglob

    ls -d !(*.cmd)


    In ksh without having to turn on anything:


    ls -d !(*.cmd)


    In zsh there is different syntax:


    ls -d *~*.cmd


    In tcsh again different syntax:


    ls -d ^*.cmd



  • by VikingOSX,

    VikingOSX VikingOSX Sep 3, 2016 5:17 AM in response to Mark Jalbert
    Level 7 (20,544 points)
    Mac OS X
    Sep 3, 2016 5:17 AM in response to Mark Jalbert

    Mark,

     

    Thanks for adding the -d switch to avoid recursive descent into directories.