Reputation: 101
the command
rm !("$filename")
does not work, because it is syntactically incorrect.
I want to remove other files in a directory but that one specified in the $filename variable.
Actually, the bash script is this:
#!/bin/bash
filename="$(ls -t | grep radar_ | head -n 1)"
echo "${filename}"
rm !("$filename")
How can I do that?
Upvotes: 1
Views: 4093
Reputation: 3838
You could try something like :
DIR="/path_to_your_dir"
for file in "${DIR}"/*; do
[[ $file = "${filename}" ]] || rm "${file}"
done
Or something like :
DIR="/path_to_your_dir"
ls -1 "${DIR}"|grep -v "${filename}"|xargs -I{} rm {}
Or something like :
find "${DIR}" ! -name "${filename}" -exec rm {} \;
find "${DIR}" ! -name "${filename}" -a -type f -exec rm {} \; # apply the rm only on files (not on the directories for example)
Personally I'd choose the find
solution to do that kind of tasks (searching and doing operation on some files).
Upvotes: 2
Reputation: 101
The shopt -s extglob
helped.
So the bash script is now:
#!/bin/bash
#set -x
shopt -s extglob
filename="$(ls -t | grep radar_ | head -n 1)"
echo "${filename}"
rm !("$filename")
Thanks Cyrus!
Upvotes: 0