2013-03-27 99 views
0

我试图从文件中除去重复项。内容是数字和名字,名字可以是(例如重复的名字):ABC ABCxxyy ABC123 ABClmn等等...(所以在这里我只想在我的文件中使用ABC)。为了得到这个,我写了下面的代码。目前它使用文件读/写。我想要使​​用数组来更改此代码,但无法计算。从bash数组中删除重复项并保存到文件

下面是当前的代码:

for h in `cat name.list` 
do 
count=`grep -c $h name.list` 
if (($count >= 1)) 
then 
    echo $h >> name.list.new   #building the new list 
    grep -v $h name.list > name.list.tmpcopy #rebuilding the name.list file... 
    mv name.list.tmpcopy name.list 
fi 
done 

我试过,但我得到了相同的原始清单作为输出:

while read line 
do 
    array+=("$line") 
done < name.list 

#loop thru the array:... 
for ((i=0; i < ${#array[*]}; i++)) 
do 
    h=${array[i]} 
    match=$(echo "${array[@]:0}" | tr " " "\n" | grep -c $h) 
    if (($match >= 1)) 
    then 
     # remove all matched names from array..... Longest match from front of string(s) 
     array=${array[@]##$h} 

     #save the current name to new array 
     array3[${#array3[*]}]=$h 
    fi 
done 

for ELEMENT in "${array3[@]}" 
do 
echo $ELEMENT 
done > name.list.new 

回答

2

试试这个:

declare -a names=($(<name.list)) 

len=${#names[@]} 

for i in $(seq 0 $len); do 
    if [ "${names[$i]}" != "" ]; then 
    m=${names[$i]} 
    for j in $(seq 0 $len); do 
     if [ $i -ne $j ]; then 
     if [ "$m" == "${names[$j]:0:${#m}}" ]; then 
      unset names[$j] 
     fi 
     fi 
    done 
    fi 
done 

for name in "${names[@]}"; do 
    echo $name 
done > name.list.new 

步骤 - 一步:

代码首先声明一个阵列

declare -a names=(...) 

并读取的name.list的内容到它:

$(<name.list) 

然后,它遍历该阵列的所有索引:

for i in $(seq 0 $len); do 
    ... 
done 

作为安全警卫空场被跳过:

if [ "${names[$i]}" != "" ]; then 
    ... 
    fi 

非空字段被读入$m(为方便起见)可变

m=${names[$i]} 

然后内部循环迭代除了当前在外环($i)处理的索引阵列的所有索引:

for j in $(seq 0 $len); do 
     if [ $i -ne $j ]; then 
     ... 
     fi 
    done 

如果字段中的索引$j第一长度OF- $m字符是相同$m该字段是REM Oved的:

 if [ "$m" == "${names[$j]:0:${#m}}" ]; then 
      unset names[$j] 
     fi 

最后剩下的值写入到输出文件:

for name in "${names[@]}"; do 
    echo $name 
done > name.list.new 
+0

谢谢。完美的作品,你可以一步一步解释吗?这样我可以在未来的解决方案中使用该学习? thx再次! – rajeev 2013-03-27 15:43:59

+0

@rajeev查看更新的答案。 – 2013-03-27 17:52:14