简体   繁体   English

如何在bash中比较变量中的两个字符串

[英]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". WEDI_RC是一个txt文件,我想一行一行地读取它,将第一列存储到变量“ name”中。 When I echo 4th line it successfully write first column ($1). 当我回显第4行时,它成功写入了第一列($ 1)。 Then I want to compare it with $list, if it matched then add it to $list and write. 然后,我想将其与$ list进行比较,如果匹配,则将其添加到$ list并编写。 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 . 如果我理解正确,则希望从文件WEDI_RC的第一列中获取唯一名称的列表。 If that is the case: 如果是这样的话:

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

Alternative 1 选择1

This can also be done without use of sort , although the order in which the names are printed is not guaranteed: 也可以不使用sort来完成,尽管不能保证名称的打印顺序:

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

Alternative 2 选择2

If it is known in advance that the names in the WEDI_RC file are sorted, then another approach is: 如果预先知道WEDI_RC文件中的名称已排序,则另一种方法是:

$ 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" "获取以空格字符分隔的第一列, sort结果进行sort以排序, sort uniq进行排序以显示uniq结果

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

Or as suggested in other answer sort -u is similar to sort | uniq 或其他答案中建议的sort -usort | uniq类似sort | uniq sort | uniq

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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