Skip to content
Advertisement

grep a file to read a key:value

I have a file file.txt which has various key:value pairs. While reading a particular value from file, more than one lines are printed. Please help me in correcting my logic below.

INPUT_FILE

cat file.txt

NAMES:1234-A0;5678-B0;3456-C0
1234-A0:1234_12345678_987

DESIRED_OUTPUT

1234_12345678_987

MY_CODE

cat file.txt | grep -w 1234-A0 | cut -f2 -d ':'

OUTPUT

1234-A0;5678-B0;3456-C0 1234_12345678_987

Please let me know what’s wrong in the above command (?) and what should be the correct command to get desired output. Thanks!

Advertisement

Answer

awk is right tool for this as your data is delimited by a common character and structured in columns and rows. You may use this awk command:

awk -F: '$1 == "1234-A0"{print $2}' file

1234_12345678_987
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement