Mik*_*lMC 9 command-line bash cp mv
假设我有一个文件夹,其中包含一些文件和一些文件夹(文件可以是任何类型)。我想使用mv/cp命令移动/复制其中一些文件和文件夹。有什么方法可以让我随机选择其中一些,就像我们使用 Ctrl 键进行选择一样,并使用终端进行移动/复制?我既不能使用通配符,也不能使用正则表达式,因为我想选择不同类型的文件,并且它们的名称有少量相似之处。
Arr*_*cal 12
如果要将所有文件移动或复制到同一目录,可以使用或-t选项,但这意味着您必须键入/提供每个文件名作为参数。它以以下方式工作,文件和参数一样多,你喜欢:cpmv
cp -t /destination/directory/ file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
或者
mv -t /destination/directory/ file1 file2 file3
Run Code Online (Sandbox Code Playgroud)
这很费力,但是使用Bash 的 tab completion可以更轻松地输入文件名。
或者,以下 bash 脚本将查找目录中的所有文件,作为第一个参数给出,并将所选文件复制到目标目录中,作为第二个参数给出。
它检查每个文件并询问您是否要复制该文件。在文件选择结束时,它会显示所选文件的列表,并询问您是否要将它们复制到目标目录:
#!/bin/bash
directory=$1
destination=$2
selected_files=()
for f in ${directory}/*
do
if [[ -f $f ]]
then
while true
do
read -p "Would you like to copy ${f}? y/n: " choice
case $choice in
y|Y) selected_files+=("$f");
break ;;
n|N) echo "${f} will not be copied.";
break ;;
*) echo "Invalid choice, enter y/n: " ;;
esac
done
fi
done
echo "The following files will be copied to ${destination}."
for file in "${selected_files[@]}"
do
echo "$file"
done
while true
do
read -p "Are these the correct files? y/n: " confirm
case $confirm in
y|Y) break ;;
n|N) echo "Exiting filechooser"; exit 1 ;;
*) echo "Invalid choice, enter y/n: " ;;
esac
done
cp -t "$destination" "${selected_files[@]}"
Run Code Online (Sandbox Code Playgroud)
请注意,此脚本中没有关于目标目录是否存在的错误检查,或者您是否输入了正确的参数。
这是一个随机选择一组要复制的文件/目录的脚本。它可以处理任意文件名,甚至包含换行符和空格的文件名。将脚本另存为~/bin/randomCopy.sh,使其可执行 ( chmod a+x ~/bin/randomCopy.sh),然后运行它,将源目录作为第一个参数,将目标目录作为第二个参数,以及文件/目录的数量(该脚本不区分文件和目录,按照您的要求)进行复制。例如,要将 5 个随机文件或目录从 复制/foo到/bar:
randomCopy.sh /foo /bar 5
Run Code Online (Sandbox Code Playgroud)
剧本:
randomCopy.sh /foo /bar 5
Run Code Online (Sandbox Code Playgroud)
请注意,如果目标目录中存在任何具有相同文件名的文件,这将覆盖现有文件。