简体   繁体   中英

How to compare two strings in variables in bash

I would like to ask one qustion: I have something like this. WEDI_RC is a txt file and I want read it line by line, take first column and store it to variable "name". When I echo 4th line it successfully write first column ($1). Then I want to compare it with $list, if it matched then add it to $list and write. It should write just one time every name. See example below:

Input:

file1 1234 5667
file1 1234 4566
file1 1234 23456
file1 1234 23467
file2 1234 23456
file3 1234 12345

Output:

file1
file2
file3

My code:

list=""
while read -r line      
        do 
            name=$(echo $line | awk -F'[ ]' '{print $1}')
            echo $name 
            if [ "$name" = "$list" ]; then
                echo $name
                list=$'$list\n$name'
                echo "$list"
            fi
    done < $WEDI_RC

If I understand correctly, you want to obtain a list of unique names from the first column of the file WEDI_RC . If that is the case:

$ awk '{print $1}' WEDI_RC | sort -u
file1
file2
file3

Alternative 1

This can also be done without use of sort , although the order in which the names are printed is not guaranteed:

$ awk '{a[$1]=1} END{for (name in a)print name}' WEDI_RC
file1
file2
file3

Alternative 2

If it is known in advance that the names in the WEDI_RC file are sorted, then another approach is:

$ awk 'prior!=$1{print $1} {prior=$1}' WEDI_RC
file1
file2
file3

If I understood your requirement, you want to show different names that appear along the first column, you can do it with something like this:

previousColumn=""

while read -r column1 column2 column3; do
    if [ "$previousColumn" != "$column1" ]; then 
        echo "$column1"
        previousColumn=$column1
    fi
done < $WEDI_RC

Back to the basics you should use cut -f1 -d" " to get the first column delimited by a space character, sort to sort the result and uniq to display uniq results

 cut -f1 -d" " WEDI_RC | sort | uniq

Or as suggested in other answer sort -u is similar to sort | uniq sort | uniq

 cut -f1 -d" " WEDI_RC | sort -u

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM