-1
Symbol  Test  
XXX,1  
GHL,2  
MKT,13  
LOC,15  
LMT,76  
TIF,45  

Shell script should return corresponding symbol for each Test.

If $Test=1,then $symbol should be XXX

how can I achieve this?

3 Answers 3

4

You can use bash associative array :

declare -A foobar
while read -r foo bar; do foobar["$bar"]="$foo"; done < <(tail -n +2 file.txt)

This will generate an associative array named foobar by reading the lines starting from second line from the file containing the key-value mapping.

Now you can declare a small function like :

choose () { echo "${foobar["$1"]}" ;}

It will output the value stored on the specified key given as first argument.

Example :

$ choose 2
GHL
$ choose 1
XXX
3
  • Interesting. note that this assumes the mapping is unique. It may be, but may not.
    – fedorqui
    Sep 7, 2015 at 22:10
  • @fedorqui yeah, it will show the last mapping in non-unique cases, i have taken OP's example literally though and the numbers should be unique btw although not sure..
    – heemayl
    Sep 7, 2015 at 22:15
  • Yes, the OP did not give much information so I think it is fine to assume it is unique. I used awk to avoid this, but it shouldn't matter. +1 for the good approach!
    – fedorqui
    Sep 7, 2015 at 22:19
1

This just needs a little bit of awk:

awk -v var=1 '$2 == var {print $1}' your_file

That is, look for the lines having the 2nd field equal to the given variable var; when this happens, print the first field.

2
  • @fedorqui...If I have the delimiter as , in my file instead of =.where should I replace?
    – canonical
    Sep 7, 2015 at 21:47
  • @canonical first of all, you should edit your question giving a real sample input. Then, you could say awk -F, '...' file.
    – fedorqui
    Sep 7, 2015 at 21:48
0

Python can do the job too:

python -c 'import sys;print [i.split(",")[0] for x,i in enumerate(sys.stdin) if x > 0 and i.strip().split(",")[1] == sys.argv[1]]' 13  < input.txt

Or as actual script:

#!/usr/bin/env python
import sys
for x,i in enumerate(sys.stdin): 
    if x > 0 and i.strip().split(",")[1] == sys.argv[1]:
         print i.strip().split(",")[0]

Test run:

$ python find_line.py 76 < input.txt                                                                                         
LMT

The way this works is simple: we redirect input.txt into script's stdin and then read it line by line, skipping first line and splitting lines into list using comma. The desired number to look up is given as first command-line argument.

It would make much easier if there wasn't the header line - that would eliminate enumerate() call, and simplify line check to if i.strip().split(",")[1] == sys.argv[1]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .