ls Filenames – How to Avoid Listing Files That End with ~ (Backup Files)

filenamesls

My requirement is to list all files in a directory, except files ending with a ~ (backup files).

I tried to use command:

ls -l | grep -v ~    

I get this output:

asdasad
asdasad~
file_names.txt
normaltest.txt
target_filename
testshell1.sh
testshell1.sh~
testshell2.sh
testshell2.sh~
testtwo.txt
testtwo.txt~
test.txt
test.txt~

I want to get only these files:

asdasad
file_names.txt
normaltest.txt
target_filename
testshell1.sh
testshell2.sh
testtwo.txt
test.txt

Best Answer

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 "~$"
Related Question