比较csv文件中的一个值,如果为true,则在同一文件中获取另一个值



我有一个输入文件:

11722550697,TEST_003,timi-export/do/ua.10451337354/11722550697
11724290732,TEST_001,timi-import/do/ca.10451337354/11724290732
11722550697,TEST_002,timi-export/do/vo.10451337354/11722550697
11724290735,TEST_005,timi-import/do/ka.10451337354/11724290732
11722550694,TEST_006,timi-import/do/tn.10451337354/11722550697
11724290733,TEST_007,timi-export/do/kl.10451337354/11724290732

我将从用户那里获得输入,我需要将其与csv文件中每行中的第二个值(TEST_00*(进行比较,然后获取第一个值,即该值的id,以供进一步处理。

注意:该文件包含此处给出的伪数据,实际数据变化很大。

使用grep和cut:

grep '^[^,]*,'$user_input, input_file | cut -d, -f1

在脚本中,您可能会使用$1而不是$user_input

请您尝试以下操作。

cat ./script.ksh
echo "Please enter a value."
read value
awk -v val="$value" -F, '$2==val{print $1}' Input_file

以下是脚本的执行过程。

./script.ksh
Please enter a value.  ##here is where user is entering value.
TEST_003
11722550697

解释:现在也添加解释。

echo "Please enter a value."  ##Using echo command for printing message for user.
read value                    ##Using read command from bash to accept value from user and keep it in value.
awk -v val="$value" -F, '     ##Starting awk program here -v val to keep bash variable in it and setting field separator as comma here.
$2==val{                      ##Checking condition here if 2nd field value is equal to val here if yes then do following.
print $1                    ##Printing first field here.
}' Input_file                 ##Mentioning Input_file name here.

假设您需要完全匹配,创建一个脚本,比如test.sh,其中包含以下内容:

awk -v input="$1" -F',' '$2==input{print $1}' input_file.csv

然后,您可以将脚本运行为:

sh test.sh TEST_003

其输出为:

11722550697

最新更新