我正在尝试执行一个命令,该命令只需针对文件中 SID 的每个不同匹配项运行一次,并且目录中存在许多共享 SID 的文件。即 SID 为 (# files )一对多
delta_12012010_part01.dat
delta_12012010_part02.dat
delta_12012010_part03.dat
delta_12022010_part01.dat
delta_12022010_part02.dat
delta_12022010_part03.dat
12012010部分是SID。上面列出了 2 个 SID,每个都有 3 个部分。 我正在运行这样的东西
find $targetdir -name "$sting*" | <some commands> | while read filename
do
SID=${filename:x:y}
if [ "$SID" -ge "$R1" ] && [ "$SID" -le "$R2" ]; then
function1 paras
function2 paras
fi
done
对于 SID 实例,Function1 只需执行一次。并且 function2 需要针对 filename 的所有实例按预期运行。 我想知道我怎样才能做到这一点
第二个想法:一种方法是将 SID 写入临时文件,然后排序 | uniq 文件并通过单独的 do while 循环运行函数 1
find $targetdir -name "$sting*" | <some commands> | while read filename
do
SID=${filename:x:y}
echo "$SID" >> tmpfile
if [ "$SID" -ge "$R1" ] && [ "$SID" -le "$R2" ]; then
# function1 paras
function2 paras
fi
done
cat tmpfile | sort | uniq | while read filename
do
function1 para
done
但是上面需要 2 个循环,而且 function1 单独工作,而不是与 function2 同时工作。所以我想,问题是有什么方法可以优雅地做到这一点。
@蒂姆·范霍文。谢谢 所以重写这将是
tmp=
find <command ...> while read filename
do
SID=${filename:x:y}
# this makes it dependent on function outcome .
# Which I dont mind actually that why I wrote it as below
{ [ "$tmp" -ne "$SID" ] ; } && { function1 paras && tmp=$SID || echo "some error msg" ; }
# this makes it independent on function outcome .
# Which will make it the equivalent of the if statement
{ [ "$tmp" -ne "$SID" ] ; } && { function1 paras || echo "some error msg" ; }
tmp=$SID
function2 paras
done
只需检查上面的内容是否正常。
最佳答案
按名称对文件进行排序,然后使用临时变量来比较 sids,仅当 sid 与临时变量不同时才运行函数 1。
osid=0
find . -name "delta*" -exec ls -1 {} \+| while read f; do
sid=$(echo $f | sed s'/.*delta_\([0-9]*\).*/\1/')
echo "Running func 2 $f $sid $osid"
if [[ "$osid" -ne "$sid" ]]; then
echo "Running func 1 $f $sid $osid"
fi
osid=$sid
done
关于shell - For循环: how to limit the activity for just 1st occurance where there are multiple matches in the loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21928151/