Avoid listing of files that end with ~ (backup files)

The GNU implementation of ls (found on most Linux systems) has an option for that: -B Ignore backups:

ls --ignore-backups

ls -l | grep -v ~

The reason this doesn't work is that the tilde gets expanded to your home directory, so grep never sees a literal tilde. (See e.g. Bash's manual on Tilde Expansion.) You need to quote it to prevent the expansion, i.e.

ls -l | grep -v "~"

Of course, this will still remove any output lines with a tilde anywhere, even in the middle of a file name or elsewhere in the ls output (though it's probably not likely to appear in usernames, dates or such). If you really only want to ignore files that end with a tilde, you can use

ls -l | grep -v "~$"

If you're using bash, make sure extglob is enabled:

shopt -s extglob

Then you can use:

ls -d -- !(*~)
  • -d to not show directories' contents
  • !(*~) all files except the ones ending with ~

On zsh, you can do the same with the kshglob option or using its own extended globs:

setopt extended_glob
ls -d -- ^*~

Since the suffix to exclude is only one character long, you could also match filenames where the last character is not the tilde (this should work without extglob, too):

ls -d -- *[^~]

But the general idea is to use ls --ignore-backups.

Tags:

Filenames

Ls