Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Say I have a piped command like this one:

$ ls -t|tail -n 10

Now if I want to remove all the files produced by the above command, if the files have spaces, it won't work:

$ rm `ls -t|tail -n 10`
# assuming the first response is 'The File Name', I get:
rm: cannot remove ‘The’: No such file or directory
rm: cannot remove ‘File’: No such file or directory
rm: cannot remove ‘Name’: No such file or directory

How can I quote the file names before sending it to rm?

share|improve this question
    
You want to set IFS to something else than whitespace. –  Hennes Jan 22 '13 at 16:13
    
@Hennes, IFS='\n' rm `ls the*` ? –  Absolute0 Jan 22 '13 at 16:17
    
That could work. IFS is the 'Internal File Separator'. It defaults to a space. You could set it to any character. Newline ('\n') and null (IFS=$'\0') ae the most often used options. (Often in combination with find -print0. -- However the best choice depends on what you are trying to do, and your example "ls|cut -d ' ' -f 3|sort|etc..." is to vague for me to comment on that. –  Hennes Jan 22 '13 at 16:23
    
$ IFS='\n' 'rm ls the*' gives me: rm: cannot remove ‘the file\nthe file2\nthe file3’: No such file or directory –  Absolute0 Jan 22 '13 at 16:26
    
For just deleting I would use something like this: find /path/to/dir -name *.avi -delete {} \;. That looks like a solution to your goal, but not one to the question asked in the OP. –  Hennes Jan 22 '13 at 16:29

1 Answer 1

up vote 1 down vote accepted

Try this one:

command that outputs files with spaces | while IFS= read -r file
do
  rm "$file"
done

The input will be split on newlines, so files with newlines in their name won't work. Quoting names with spaces works without problems though.

share|improve this answer
    
Not so for backslashes. The quoting is OK as long as you use while (which you very correctly do), it will break with for. –  terdon Jan 22 '13 at 16:16
    
@Peter, any way to the same without the loop? –  Absolute0 Jan 22 '13 at 16:21
    
@Absolute0, you can avoid the loop by quoting the command as described in my answer. It is not a good idea though, the loop is safer if dealing with weird characters. –  terdon Jan 22 '13 at 16:26
    
@Absolute0 Did this really work for you? If a file contains a space, it won't even pass through cut -d ' ' properly. –  slhck Jan 22 '13 at 16:56
    
@slhck, I wasn't actually using cut--I was trying to formulate some complex command. Should have gone with my actual command. –  Absolute0 Jan 23 '13 at 13:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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