Yash
Yash

Reputation: 3114

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!

Upvotes: 1

Views: 1474

Answers (2)

gildux
gildux

Reputation: 564

First,

Please let me know what's wrong in the above command

When you wrote cat file.txt | grep -w 1234-A0 it should be grep -w 1234-A0 file.txt (I mean it's useless to pipe from cat into a command that can directly read file, plus you're eating some piece of precious ressources while making your script sub-optimal)
That being said, you asked for lines with word "1234-A0" ...and that's exactly your output! Now try the following and note down the differences:

  • grep ':1234-A0' file.txt (you should have the first line)
  • grep '1234-A0:' file.txt (you should have the second one)
  • grep '^1234-A0' file.txt (second line too)

Add more lines, with "1234-A0" randomly elsewhere in the file and rerun the examples above to see the differences.

Last,

what should be the correct command

Once you give the right pattern, you can now pipe to cut as you did: grep '^1234-A0:' file.txt | cut -f2 -d: for example.

AWK language is another way to go, more concise, but not for now as you are still learning BRE (also found in sed and vi, whereas awk uses ERE)

Upvotes: 1

anubhava
anubhava

Reputation: 785098

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

Upvotes: 1

Related Questions