我有一个脚本,首先将选定的文件移动到临时目录中,扫描该目录,获取最大的文件并使用该名称创建一个新目录,然后将所有文件移动到新创建的目录中。
但当遇到包含 ' 字符的目录或文件时,例如单词是 我认为这可能与 jfilenameall 没有正确“引用”有关,我已经测试了几种方法,但还没有成功。
有人知道我做错了什么吗?
值得一提是我正在通过 nemo 操作运行此脚本,因此执行以下命令行:
script.sh "path/filename1.txt" "path/filename2.txt"
..依此类推,具体取决于在 gui 中选择的文件数量
jdir2="$1"
jdirfirst="${jdir2%/*}"
jdir="$jdirfirst"/
jdir0="$jdirfirst"
tmpdir="$jdir0/tmp.tmp3"
mkdir "$tmpdir"
mv "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$tmpdir"/
jfilenameall=$(basename $(find $tmpdir -maxdepth 1 -type f -printf "%s\t%p\n" | sort -n | tail -1 | awk '{print $NF}'))
jfilename="${jfilenameall::-4}"
jfilenameextension="$(echo -n $jfilenameall | tail -c 3)"
jfilename=${jdirlast::-4}
mkdir "$jdir0/$jfilename"
mv "$jdir0/tmp.tmp3/"* "$jdir0/$jfilename/"
答案1
这将执行您的问题所描述的操作(我删除了您的一些步骤,因为它们似乎没有必要)。请注意,它假设您使用的是 GNU 工具。主要问题是您没有双引号变量和命令替换。我还为一些更奇怪的文件名做了这项工作,例如包含换行符或以以下内容开头的文件名-
:
#!/bin/bash
## You don't define $jdir0 in your script, so I am assuming you
## do so earlier. I'm setting it to '/tmp' here.
jdir0="/tmp"
## Create a temp dir in $jdir0
tmpdir=$(mktemp -dp "$jdir0")
## Move all arguments passed to the script to the tmp dir,
## this way you don't need to specify $1, $2 etc. The -- ensures
## this will work even if your file names start with '-'.
mv -- "$@" "$tmpdir"/
## Get the largest file's name. Assume GNU find; deal with arbitrary file names,
## including those with spaces, quotes, globbing characters or newlines
IFS= read -r -d '' jfilenameall < <(find "$tmpdir" -maxdepth 1 -type f \
-printf '%s\t%p\0' | sort -zn |
tail -zn1 | cut -f 2-)
## Assume GNU find; deal with arbitrary file names, including those with
## spaces, quotes, globbing characters or newlines
jfilenameall="$(basename "$jfilenameall")"
## Get the extension: whatever comes after the last . in the file name. You don't
## use this anywhere, but maybe you just don't show it. If the file has no extension,
## this variable will be set to the entire file name.
jfilenameextension="${jfilenameall##*.}"
## get the file name without the extension. Don't assume an extension will always be 3 chars
jfilename="${jfilenameall%.*}"
## You don't define $jdir0 in your script. I am assuming you do so earlier
mkdir -p "$jdir0/$jfilename"
mv -- "$tmpdir/"* "$jdir0/$jfilename/"
## remove the now empty tmp dir
rmdir "$tmpdir"