How to use grep or awk to get particular numbers from a file and put them in a text file?

I have the following file "file.log" :

ABC : 1
XYZ : 10
MMM : 3

ABC : 4
XYZ : 22
MMM : 5

ABC : 22
XYZ : 1
MMM : 3

... and so on

I am trying to write a bash script that will check each of the lines with ABC and MMM (don't need XYZ) and only grab the integers ( e.g. 1, 4 and 22 for ABC and 3,5 and 3 for MMM) and put them all in a txt file , say, solution.txt.

I am using the following command :

cat file.log | grep "ABC" | grep -o '[0-9]\+' > solution.txt

But this only prints out the integers for ABC in order i.e

1
4
22

However I want them to be ABC followed by MMM in order as it appears in "file.log"

desired output :

1
3
4
5
22
5

Do I need to put grep in a loop to go only by one line after the other or if it can be combined with "awk" the problem can be solved ?

Thanks.



Read more here: https://stackoverflow.com/questions/66326823/how-to-use-grep-or-awk-to-get-particular-numbers-from-a-file-and-put-them-in-a-t

Content Attribution

This content was originally published by 2014GAM at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: