使用 rm 删除多个文件,只需一次确认即可(rm -i)?

使用 rm 删除多个文件,只需一次确认即可(rm -i)?

我有一个别名rm='rm -irv',我想删除一堆文件和/或目录,但我只想要 1 条确认消息,例如rm: descend into directory 'myfolder'?

我不介意确认每个目录,但不介意确认每个目录中的每个文件。rm *或 的zsh 功能rm something/*运行良好,但有时我只是删除文件rm *.txt或单个文件rm document.txt,但我仍然希望至少有 1 个确认。

这个解决方案 非常接近我正在寻找的东西,但并不适用于所有情况。假设目录“myfolder”包含 100 个文件,那么我想要如下所示的文件:

~ > ls -F
myfolder/    empty.txt    file.txt    main.c

~ > rm *
zsh: sure you want to delete all 4 files in /home/user [yn]? n

~ > rm myfolder
rm: descend into directory 'myfolder'? y
removed 'file1.txt'
removed 'file2.txt'
...
removed 'file100.txt'
removed directory 'myfolder'

~ > rm main.c
rm: remove regular file 'main.c'? y
removed 'main.c'

~> rm *.txt
rm: remove all '*.txt' files? y
removed 'empty.txt'
removed 'file.txt'

答案1

获得问题中列出的确切提示和输出实际上是不可能的(或者是大量的工作),但以下内容应该涵盖所有实际目的:

# Disable the default prompt that says
# 'zsh: sure you want to delete all 4 files in /home/user [yn]?'
setopt rmstarsilent

# For portability, use the `zf_rm` builtin instead of any external `rm` command.
zmodload -Fa zsh/files b:zf_rm

rm() {
  # For portability, reset all options (in this function only).
  emulate -L zsh

  # Divide the files into dirs and other files.
  # $^ treats the array as a brace expansion.
  # (N) eliminates non-existing matches.
  # (-/) matches dirs, incl. symlinks pointing to dirs.
  # (-^/) matches everything else.
  # (T) appends file type markers to the file names.
  local -a dirs=( $^@(TN-/) ) files=( $^@(TN-^/) )

  # Tell the user how many dirs and files would be deleted.
  print "Sure you want to delete these $#dirs dirs and $#files files in $PWD?"

  # List the files in columns à la `ls`, dirs first.
  print -c - $dirs $files

  # Prompt the user to confirm.
  # If `y`, delete the files.
  #   -f skips any confirmation.
  #   -r recurses into directories.
  #   -s makes sure we don't accidentally the whole thing.
  # If this succeeds, print a confirmation.
  read -q "?[yn] " &&
      zf_rm -frs - $@ && 
      print -l '' "$#dirs dirs and $#files files deleted from $PWD."
}

有关 的更多信息zf_rm,请参阅http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002files-Module

有关 glob 限定符的更多信息(TN-^/)可以在这里找到:http://zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Qualifiers

相关内容