ls (parameters if needed) >my.file
(edit my.file to remove the specific file)
xargs <my.file rm
To test, replace "rm" with "echo" and it will list the files to be removed.
Note my.file should contain only file names. If it was a full listing, the vi command of "1,$s/^.* //" should fix it. Note the space after the asterisk.
A bit out of box and assuming that you want to retain the most recently modified file, rename the file you want to keep by giving it a leading dot, then remove everything else and rename the file back:-
# Work out file to be retained
save_file="$(ls -1rt |tail -1)"
mv "$save_file" ".$save_file"
# Delete everything else
rm *
# Move my file back
mv ".$save_file" "$save_file"
Would that work for you?
Perhaps also, list the files, stripping out the most recent:-
IMHO I think directly giving rm * could be dangerous in case we are not running the script in the same path where user actually wants to perform the actions. So I believe it will more good if we could add path here and check the condition if path exist too(my fav. Bakunin style :))
if [[ -d /my/path/for/actions_to_be_performed/ ]]
then
cd /my/path/for/actions_to_be_performed/
rm * ### Or whatever action needed by user
else
echo "Path /my/path/for/actions_to_be_performed/ does not exist."
fi
Given the small number of files that you want to remove:
rm -i *
would suffice. Alternatively you could remove the write-attribute of the file(s) you wish to preserve. This would cause rm to prompt for their removal whilst quietly removing all other files. Just remember to put it back afterwards.
If you have a varying list of files whose names all begin with MM_ and you want to remove all but the last name sorted alphanumerically, none of the filenames contain any IFS characters (by default <space>, <tab>, and <newline>), the list of files you're removing will never give you a command length that would exceed ARG_MAX , and you're using a shell that meets POSIX shell requirements (with or without extensions like shopt and setopt ). You could also try:
last=''
list=''
for file in MM_6000*
do list="$list $last"
last="$file"
done
[ ${#list} -gt 0 ] && rm $list
which is similar to what Corona688 suggested, but only invokes rm once instead of once for each file to be removed. (But his suggestion works without the limitations noted above except the 1st and last.)
Note: The problem noted by MadeInGermany in post #13 in this thread has been fixed above.
Not quite. If you run my (corrected) script twice, the 2nd execution will silently do nothing (since only one matching file remains). The code above will run rm with no file operands the 2nd time you run it (or any time that there are no files or only one file matching the pattern MM_6000* ). And MadeInGermany's code has this same issue.