2

I have a list of file names of files i need to delete.

Is there a way to write a batch file that i can specify Linux to delete these files with the given names?

3 Answers 3

6

You can simply call:

\rm -f $(<file.txt)

To remove all the files listed in a file called file.txt (1 per line of course).

Sign up to request clarification or add additional context in comments.

4 Comments

How can i make sure these files are being removed?
Instead of \rm -f you can use \rm -i and that will show each and every file to you and ask for confirmation before removing.
@anubhava Can you please explain the command. What happens if the command is prepended with backslash? Won't this command fail for a very large file?
@AbhijeetRastogi: Backslash before any command makes sure that your local alias are ignored as many people alias rm, cp, mv etc commands in their local .bashrc, .profile. If list of files to be deleted is huge in input huge then it is better to delete files in a loop.
3

Say you have a file "file":

foobar.txt
frob
media/music.m3u

Then you can pipe the contents to xargs, which will append the piped-in stuff line per line to the argument specified, and execute it:

cat file | xargs rm

Comments

2

As a bash one liner

cat yourfile.txt |while read line; do rm ${line}; done

8 Comments

So i would need to add a bunch of these lines with the file names? And what do i name the batch file and how do i run it in terminal?
The principle is the same as presnel's I believe (xargs is pretty neat). You said you have a list of files, create some file "yourfile.txt" with all the filenames listed, then run the command at a bash prompt.
Understood because i have about 30,000 files i need to delete haha.
I put my text file in the folder of the images. i had it formatted with the image file names for example name.jpg going down line by line. but when i ran it i get this. rm: cannot lstat 6td2h4mk.jpg': No such file or directory` for all of them specified to their file names
You might need to run fsck. I've also had to put ${line} in quotes before... like: do rm -i "${FILE}";
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.