help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Comparing arrays


From: Chris Down
Subject: Re: [Help-bash] Comparing arrays
Date: Mon, 1 Apr 2013 10:21:28 +0800
User-agent: Mutt/1.5.21 (2010-09-15)

On 2013-03-31 15:34, Jerry wrote:
> Now, what I am attempting to do is check the list of existing files
> "Old_Files" against the list of "New_Files". If any of the files in
> "Old_Files" does not exist in the "New_Files" list, it is to be
> deleted. I have come up with some very laborious methods of doing this,
> but I am sure that there has to be a simpler way. I would like to make
> this a function also so I could call it from anywhere in the script.

If I've understood correctly:

    newFiles=(foo baz)
    oldFiles=(foo bar baz qux)

    for oldFile in "address@hidden"; do
        found=0
        for newFile in "address@hidden"; do
            if [[ "$oldFile" == "$newFile" ]]; then
                found=1
                break
            fi
        done
        (( found )) || rm "$oldFile"
    done

Making it a function is slightly more difficult, as you need to separate the
arrays. This exploits the fact that Unix filenames aren't allowed to be
0-length:

    newFiles=(foo baz)
    oldFiles=(foo bar baz qux)

    deleteOld() {
        local oldFiles=()
        local newFiles=()
        local pivoted=0

        for arg do
            if [[ "$arg" == "" ]]; then
                pivoted=1
            fi

            if (( pivoted )); then
                newFiles+=( "$arg" )
            else
                oldFiles+=( "$arg" )
            fi
        done

        for oldFile in "address@hidden"; do
            found=0
            for newFile in "address@hidden"; do
                if [[ "$oldFile" == "$newFile" ]]; then
                    found=1
                    break
                fi
            done
            (( found )) || rm "$oldFile"
        done
    }

    deleteOld "address@hidden" "" "address@hidden"

Chris

Attachment: pgp7zrFC4mahh.pgp
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]