Vandhana
Vandhana

Reputation: 135

Compare a value in csv file if true then fetch another value in the same file

I have an input file as:

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

I will get the input from the user, and i need to compare that with the second value present in the csv file in each line (TEST_00*) and than fetch the first value, which is the id for that value for further processing.

Note:The file contains dummy data given here, and actual data varies lot.

Upvotes: 0

Views: 166

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133680

Could you please try following.

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

Following will be the execution of the script.

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

Explanation: Adding explanation too now.

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.

Upvotes: 2

Samarth
Samarth

Reputation: 687

Assuming you need exact match, create a script, lets say test.sh with the following contents:

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

Then, you can run the script as:

sh test.sh TEST_003

which will give the output as:

11722550697

Upvotes: 1

perreal
perreal

Reputation: 98088

Using grep and cut:

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

In a script you will probably use $1 instead of $user_input.

Upvotes: 2

Related Questions