列出名称长度在 3 到 6 个字符之间的所有文件
List all files with length of name between 3 and 6 characters
我必须为 class 编写一些 shell 脚本,而且由于只有在线讲座,我无法向我的教授寻求帮助。
任务(应该是)其实很简单:
Write a shell script which lists all files in the current directory, whose name is greater than 3 and smaller than 6 characters
12.txt
--> should not be listed
123.txt
--> should be not listed
1234567.txt
--> should not be listed
12345.txt
--> should be listed
123456.txt
--> should be listed
问题中没有给出后缀(文件扩展名).txt
,这只是我举的例子。所有文件的列表应该适用于任何后缀。
如果有人能帮助我理解正确的命令,我会很高兴,或者 post link 教程等
效率不高,但有助于理解,循环遍历目录中的每个.txt文件并一一过滤:
cd yourpath/dir
for i in *.txt;
do
new_Val="${i%.*}"
if (( ${#new_Val} >3 && ${#new_Val} <6 ));
then
echo "${i}"
fi
done
删除后缀 .txt
: ${i%.*}
名称长度:${#new_Val}
输入:
1234567.txt
12345.txt
123aaaa.txt
123aa.txt
1234.txt
输出:
12345.txt
123aa.txt
1234.txt
根据你给出的例子,我推断你想列出所有 base 名称在删除后缀 .*
后是 3 到 6 个字符的文件,我会简单地做:
ls ??{?,??,???,????}.* 2> /dev/null
已编辑:我将重定向添加到 /dev/null
以避免错误消息,作为下面评论和其他人建议的结果。
假设您的目录包含以下文件:
1234567.txt
123456.txt
12345.txt
1234.txt
123.txt
12.txt
输出将是:
123456.txt 12345.txt 1234.txt 123.txt
解释:?
匹配任意字符,{a,b}
匹配a
或b
。所以 {?,??}
匹配任何一个或两个字符的序列。只需根据您的情况推断:3 到 6 个字符与 2 个字符后跟 1、2、3 或 4 个字符相同。
shopt -s extglob
ls ??@(?|??|???|????).* 2>/dev/null
在zsh
中,它只是
setopt extended_glob
print -l ?(#c4,5).*
模式 ?(#c4,5)
匹配 4 或 5 个字符。
我必须为 class 编写一些 shell 脚本,而且由于只有在线讲座,我无法向我的教授寻求帮助。
任务(应该是)其实很简单:
Write a shell script which lists all files in the current directory, whose name is greater than 3 and smaller than 6 characters
12.txt
--> should not be listed
123.txt
--> should be not listed
1234567.txt
--> should not be listed
12345.txt
--> should be listed
123456.txt
--> should be listed
问题中没有给出后缀(文件扩展名).txt
,这只是我举的例子。所有文件的列表应该适用于任何后缀。
如果有人能帮助我理解正确的命令,我会很高兴,或者 post link 教程等
效率不高,但有助于理解,循环遍历目录中的每个.txt文件并一一过滤:
cd yourpath/dir
for i in *.txt;
do
new_Val="${i%.*}"
if (( ${#new_Val} >3 && ${#new_Val} <6 ));
then
echo "${i}"
fi
done
删除后缀 .txt
: ${i%.*}
名称长度:${#new_Val}
输入:
1234567.txt
12345.txt
123aaaa.txt
123aa.txt
1234.txt
输出:
12345.txt
123aa.txt
1234.txt
根据你给出的例子,我推断你想列出所有 base 名称在删除后缀 .*
后是 3 到 6 个字符的文件,我会简单地做:
ls ??{?,??,???,????}.* 2> /dev/null
已编辑:我将重定向添加到 /dev/null
以避免错误消息,作为下面评论和其他人建议的结果。
假设您的目录包含以下文件:
1234567.txt
123456.txt
12345.txt
1234.txt
123.txt
12.txt
输出将是:
123456.txt 12345.txt 1234.txt 123.txt
解释:?
匹配任意字符,{a,b}
匹配a
或b
。所以 {?,??}
匹配任何一个或两个字符的序列。只需根据您的情况推断:3 到 6 个字符与 2 个字符后跟 1、2、3 或 4 个字符相同。
shopt -s extglob
ls ??@(?|??|???|????).* 2>/dev/null
在zsh
中,它只是
setopt extended_glob
print -l ?(#c4,5).*
模式 ?(#c4,5)
匹配 4 或 5 个字符。