这里我提供数组变量:
- users
- $uid ....
- rooms
- $roomid
- info
- title
- description
- ....
- messages
- $messageid
- ....
- users
我有一些下面提到的文件列表,所以我需要从这些文件列表中提取匹配的文件:
这里我提供了一些文件列表:
arryFilePrefix=('State','Statement','Sense','Senseful','view_Model')
我需要应用循环和grep,这样对于每个循环转,我可以提取匹配的一个。
我尝试使用以下代码:
$ls home/fileScript
State_6721_4568
State_8888_9999
Statement_1231_2369
Sense_1231_2369
Sense_1231_5678
Senseful_3453_2211
view_Model_1212_1111
view_Model_1231_2369
view_Model_8521_4421
但输出是:
arryFilePrefix=('State','Statement','Sense','Senseful','view_Model')
for arg in "${arryFilePrefix[@]}";
do
var=$(ls home/fileScript | grep "^$arg");
echo "$arg matched files are : $var"
done
如果我们观察到上面的输出,我得到的是Statement和Senseful也出现在State和Sense匹配的文件中,这些文件实际上并不正确。
所以请帮助我如何从给定的文件列表中仅提取匹配的文件。
答案 0 :(得分:1)
数组声明的正确语法是:
arryFilePrefix=('State' 'Statement' 'Sense' 'Senseful' 'view_Model')
并将其用作:
for arg in "${arryFilePrefix[@]}"; do
printf '\n%s matched files are :\n' "$arg"
printf '%s\n' /home/fileScript/"${arg}_"*
done
<强>输出:强>
State matched files are :
/home/fileScript/State_6721_4568
/home/fileScript/State_8888_9999
Statement matched files are :
/home/fileScript/Statement_1231_2369
Sense matched files are :
/home/fileScript/Sense_1231_2369
/home/fileScript/Sense_1231_5678
Senseful matched files are :
/home/fileScript/Senseful_3453_2211
view_Model matched files are :
/home/fileScript/view_Model_1212_1111
/home/fileScript/view_Model_1231_2369
/home/fileScript/view_Model_8521_4421
答案 1 :(得分:0)
您可以按以下方式修改代码:
1.按照Anubhava的建议定义阵列
2.只需将grep命令从grep "^$arg"
更改为grep "^$arg[_]"
即可。 (因为您的文件名在首字母后面有_
。)
原始代码的其余部分很好,它应该按预期工作。
以下是原始代码,其中包含建议的更改以及输出:
arryFilePrefix=('State' 'Statement' 'Sense' 'Senseful' 'view_Model')
for arg in "${arryFilePrefix[@]}";
do
var=$(ls home/fileScript | grep "^$arg[_]");
echo -e "$arg matched files are :\n$var\n" # -e enables escape characters (here for \n)
done
输出:
State matched files are :
State_6721_4568
State_8888_9999
Statement matched files are :
Statement_1231_2369
Sense matched files are :
Sense_1231_2369
Sense_1231_5678
Senseful matched files are :
Senseful_3453_2211
view_Model matched files are :
view_Model_1212_1111
view_Model_1231_2369
view_Model_8521_4421