Monday, May 20, 2024
36
rated 0 times [  36] [ 0]  / answers: 1 / hits: 34499  / 1 Year ago, wed, april 12, 2023, 4:20:42

I have a text file that has a list of paths to various files. Is there a command I can use that will iterate through each line and delete the file at the stated path?


More From » command-line

 Answers
6

Use xargs:



xargs rm < file  # or
xargs -a file rm


But that will not work if the file names/paths contain characters that should be escaped.



If your filenames don't have newlines, you can do:



tr '
' '0' < file | xargs -0 rm # or
xargs -a file -I{} rm {}


Alternatively, you can create the following script:



#!/bin/bash

if [ -z "$1" ]; then
echo -e "Usage: $(basename $0) FILE
"
exit 1
fi

if [ ! -e "$1" ]; then
echo -e "$1: File doesn't exist.
"
exit 1
fi

while read -r line; do
[ -n "$line" ] && rm -- "$line"
done < "$1"


Save it as /usr/local/bin/delete-from, grant it execution permission:



sudo chmod +x /usr/local/bin/delete-from


Then run it with:



delete-from /path/to/file/with/list/of/files

[#20956] Thursday, April 13, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
singerrupt

Total Points: 435
Total Questions: 111
Total Answers: 109

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;