Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash-向rm传递一个文件名,该文件名位于变量中,但带有!选项_Bash_Rm - Fatal编程技术网

Bash-向rm传递一个文件名,该文件名位于变量中,但带有!选项

Bash-向rm传递一个文件名,该文件名位于变量中,但带有!选项,bash,rm,Bash,Rm,命令 rm !("$filename") 不起作用,因为它在语法上不正确 我想删除目录中的其他文件,但$filename变量中指定的文件除外 实际上,bash脚本是这样的: #!/bin/bash filename="$(ls -t | grep radar_ | head -n 1)" echo "${filename}" rm !("$filename") 我该怎么做呢?您可以尝试以下方法: DIR="/path_to_your_dir" for file in "${DIR}"/

命令

rm  !("$filename")
不起作用,因为它在语法上不正确

我想删除目录中的其他文件,但$filename变量中指定的文件除外

实际上,bash脚本是这样的:

#!/bin/bash

filename="$(ls -t | grep radar_ | head -n 1)"
echo "${filename}"
rm  !("$filename")

我该怎么做呢?

您可以尝试以下方法:

DIR="/path_to_your_dir"
for file in "${DIR}"/*; do 
  [[ $file = "${filename}" ]] || rm "${file}"
done
DIR="/path_to_your_dir"
ls -1 "${DIR}"|grep -v "${filename}"|xargs -I{} rm {}
 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)
或者类似于:

DIR="/path_to_your_dir"
for file in "${DIR}"/*; do 
  [[ $file = "${filename}" ]] || rm "${file}"
done
DIR="/path_to_your_dir"
ls -1 "${DIR}"|grep -v "${filename}"|xargs -I{} rm {}
 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)
或者类似于:

DIR="/path_to_your_dir"
for file in "${DIR}"/*; do 
  [[ $file = "${filename}" ]] || rm "${file}"
done
DIR="/path_to_your_dir"
ls -1 "${DIR}"|grep -v "${filename}"|xargs -I{} rm {}
 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)

就我个人而言,我会选择
find
解决方案来完成这类任务(搜索并对某些文件执行操作)。

shopt-s extglob有帮助

因此,bash脚本现在是:

#!/bin/bash

#set -x

shopt -s extglob

filename="$(ls -t | grep radar_ | head -n 1)"
echo "${filename}"
rm  !("$filename")

谢谢你,赛勒斯

可能需要打开extglob。请参见
shopt-extglob
shopt-s extglob
。添加
shopt-s extglob
帮助。但是脚本会删除$filename变量中指定的文件以外的任何文件。所以这不是解决方案。
find“${DIR}”-名称“${filename}”-类型f-exec rm{}\从目录中删除所有内容,而不保留$filename变量中指定的文件。我在这里遗漏了什么?@PalCsanyi尝试删除
-type f
或在这两个条件之间添加
-a
。@Idriss Neumann非常感谢。
-a
解决了我的问题。甚至不应该考虑使用
ls
;你应该去掉那个例子。@chepner关于这个我没有你那么明确。我的意思是肯定的,当然在脚本中使用
ls
通常会导致一些错误,比如著名的$(ls…
中的
for I,当文件名包含空格时,它就不能正常工作。但我使用它的方式并非如此。这个版本的目的是展示我们如何处理
grep-v
xargs
。我说我更喜欢使用
find
来完成这类任务;)