Shell script to get one column value(s)

Hello Gurus,

I have limited experience in writing UNIX scripting. Have business requirement to get one column data from a file. My file format is,

FileName: /root/dir1/scripts/DSList.txt

colA | colB
SEQ_A | JOB_1a
SEQ_B | JOB_1b
SEQ_B | JOB_2b
SEQ_B | JOB_3b
SEQ_C | JOB_1c

From above format, read the file where colA = ${variable_name} then get colB values display one-by-one using FOR loop.

Please advise me how to write for loop by checking the first field with a variable name.

Thanks in advance.

  • Venkat

Please use code tags as reuqired by forum rules!

Try (untested)

awk -F\| -vSL=${variable_name} '$1 == SL {print $2}' file

Thank you RudiC. Is there alternative that I can pass this code by For-loop as well?

I don't understand. What keeps you from using command substitution?

Small change to RudiC's suggestion, otherwise it will not work...

awk -F'[ \t]*[|][ \t]*' -v SL=${variable_name} '$1 == SL {print $2}' file

Or you could try this:

while IFS="|$IFS" read colA colB
do 
  if [ "$colA" =  "$variable_name" ]; then
    echo "$colB"
  fi
done < file