删除配置文件中提到的文件以外的所有文件 [英] Deleting all files except ones mentioned in config file
问题描述
情况:
我需要一个bash脚本,该脚本删除当前文件夹中的所有文件,但在名为" .rmignore "的文件中提及的所有文件除外.该文件可能包含相对于当前文件夹的地址,也可能包含星号(*).例如:
I need a bash script that deletes all files in the current folder, except all the files mentioned in a file called ".rmignore". This file may contain addresses relative to the current folder, that might also contain asterisks(*). For example:
1.php
2/1.php
1/*.php
我尝试过的事情:
- 我尝试使用
GLOBIGNORE
,但是效果不佳. -
我还尝试将
find
与grep
一起使用,如下所示:
- I tried to use
GLOBIGNORE
but that didn't work well. I also tried to use
find
withgrep
, like follows:
find . | grep -Fxv $(echo $(cat .rmignore) | tr ' ' "\n")
推荐答案
将find
的出口通过管道传递到另一个命令被认为是不好的做法.可以在命令后使用-exec
,-execdir
和'{}'
作为文件的占位符,并使用';'
指示命令的结尾.您还可以使用'+'
将命令与IIRC一起传递.
It is considered bad practice to pipe the exit of find
to another command. You can use -exec
, -execdir
followed by the command and '{}'
as a placeholder for the file, and ';'
to indicate the end of your command. You can also use '+'
to pipe commands together IIRC.
在这种情况下,您希望列出目录的所有内容,并逐个删除文件.
In your case, you want to list all the contend of a directory, and remove files one by one.
#!/usr/bin/env bash
set -o nounset
set -o errexit
shopt -s nullglob # allows glob to expand to nothing if no match
shopt -s globstar # process recursively current directory
my:rm_all() {
local ignore_file=".rmignore"
local ignore_array=()
while read -r glob; # Generate files list
do
ignore_array+=(${glob});
done < "${ignore_file}"
echo "${ignore_array[@]}"
for file in **; # iterate over all the content of the current directory
do
if [ -f "${file}" ]; # file exist and is file
then
local do_rmfile=true;
# Remove only if matches regex
for ignore in "${ignore_array[@]}"; # Iterate over files to keep
do
[[ "${file}" == "${ignore}" ]] && do_rmfile=false; #rm ${file};
done
${do_rmfile} && echo "Removing ${file}"
fi
done
}
my:rm_all;
这篇关于删除配置文件中提到的文件以外的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!