说我们有一个名为randomfile_a434534_Frank.csv
的文件我希望用户输入第一部分“randomfile *”作为参数而不是整个事物。如何在不指定整个文件名的情况下访问/说删除此特定文件
答案 0 :(得分:4)
以下重新命名,直到给出仅匹配单个文件的前缀。修改以尝试 - 如果您只想测试一次,则删除循环,如果您想从命令行获取前缀,则转而使用$1
,或者在多个文件的情况下迭代"${files[@]}"
如果这是你的意图,那就是匹配而不是哄骗/重新投入。
#!/bin/bash
# note that the above is necessary to enable features such as arrays; shells started
# with #!/bin/sh may not provide them.
while :; do
echo "Please enter a filename prefix:" >&2
IFS= read -r filename
files=( "$filename"* )
if (( ${#files[@]} == 1 )) && [[ -e "$files" ]]; then
echo "OK; using $files" >&2
break
elif [[ ! -e "$files" ]] || (( ${#files[@]} == 0 )); then
echo "Error: No matching files found" >&2
else
echo "Error: More than one file matches that prefix" >&2
fi
done
echo "Operating on file named: $files"
答案 1 :(得分:0)
您可以使用rm "$intput"*
的用户输入(如果您希望用户检查哪些文件正在被删除,则使用-i),但要注意实际的用户输入,这可能会导致您的脚本出现意外情况。
这是一个小贝壳概念证明:
$ touch aaJKL
$ toto=aa
$ rm -i "$toto"* # thanks Charles Duffy
rm: remove regular empty file `aaJKL'? y
会发生什么?
./; <<nasty command>>; echo "
并执行任意命令system()
的字符串,或者使用eval
强制执行额外的解析传递时。)另一个提示是向用户提示inode编号,并确保此inode编号合法。
例如,您可以执行以下操作:
#!/usr/bin/env bash
echo "Choose a single file number you want to remove"
ls -i1 ./
read filenumber
if [[ $filenumber =~ ^[-+]?[0-9]+$ ]]; then
find . -inum $filenumber -delete
else
echo "Expect integer as an input"
fi
示例输出:
$ touch sample{1,2,3,4}
$ ./so.sh
Choose a single file number you want to remove
1614159 sample1
1614160 sample2
1614161 sample3
1614162 sample4
fds
Expect integer as an input
$ ./so.sh
Choose a single file number you want to remove
1614159 sample1
1614160 sample2
1614161 sample3
1614162 sample4
1614159
$ ./so.sh # notice that sample1 was deleted
Choose a single file number you want to remove
1614160 sample2
1614161 sample3
1614162 sample4