【问题标题】:Comparing arrays in shell比较shell中的数组
【发布时间】:2013-12-10 15:51:51
【问题描述】:

我正在编写如下的 shell 脚本,它获取用户在文件中提供的文件列表,然后 ftp 到服务器,然后将文件列表与服务器上的文件列表进行比较。我遇到的问题是,当我调用 diff 函数时,返回的列表是两个数组唯一的文件。我只想要那些在 unique_array1 但不在 unique_array2 中的。简而言之,一个列表显示用户提供的列表中的哪些文件不在 ftp 服务器上。请注意,在用户提供的文件列表中,每一行都是一个文件名,以换行符分隔。我的脚本如下:

    #!/bin/bash

    SERVER=ftp://localhost
    USER=anonymous
    PASS=password
    EXT=txt
    FILELISTTOCHECK="ftpFileList.txt"

    #create a list of files that is on the ftp server
    listOfFiles=$(curl $SERVER --user $USER:$PASS 2> /dev/null | awk '{ print $9 }' | grep -E "*.$EXT$")

    #read the list of files from the list provided##
    #Eg:
    # 1.txt
    # 2.txt
    # 3.txt
    #################################################
    listOfFilesToCheck=`cat $FILELISTTOCHECK`

    unique_array1=$(echo $listOfFiles | sort -u)
    unique_array2=$(echo $listOfFilesToCheck | sort -u)
    diff(){
     awk 'BEGIN{RS=ORS=" "}
      {NR==FNR?a[$0]++:a[$0]--}
      END{for(k in a)if(a[k])print k}' <(echo -n "${!1}") <(echo -n "${!2}")
    }

    #Call the diff function above
    Array3=($(diff unique_array1[@] unique_array2[@]))

    #get what files are in listOfFiles but not in listOfFilesToCheck
    echo ${Array3[@]}

【问题讨论】:

    标签: arrays bash shell compare


    【解决方案1】:

    基于this你可以试试comm命令:

    Usage: comm [OPTION]... FILE1 FILE2
    Compare sorted files FILE1 and FILE2 line by line.
    
    With no options, produce three-column output.  Column one contains
    lines unique to FILE1, column two contains lines unique to FILE2,
    and column three contains lines common to both files.
    
      -1              suppress column 1 (lines unique to FILE1)
      -2              suppress column 2 (lines unique to FILE2)
      -3              suppress column 3 (lines that appear in both files)
    

    一个测试程序:

    #!/bin/bash
    
    declare -a arr1
    declare -a arr2
    
    arr1[0]="this"
    arr1[1]="is"
    arr1[2]="a"
    arr1[3]="test"
    
    arr2[0]="test"
    arr2[1]="is"
    
    unique_array1=$(printf "%s\n" "${arr1[@]}" | sort -u)
    unique_array2=$(printf "%s\n" "${arr2[@]}" | sort -u)
    
    comm -23 <(printf "%s\n" "${unique_array1[@]}") <(printf "%s\n" "${unique_array2[@]}")
    

    输出:

    a
    this
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 2021-10-12
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2010-10-17
      相关资源
      最近更新 更多