Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use awk to find first occurrence only of string after a delimiter

Tags:

bash

awk

I have a bunch of documents that all have the line, Account number: 123456789 in various locations.

What I need to do is be able to parse through the files, and find the account number itself. So, awk needs to look for Account number: and return the string immediately following.

For example, if it was:

Account number: 1234567 

awk should return:

1234567 

Once it's found the first occurrence it can stop looking.

But, I'm stumped. What's the right way to do this using awk?

like image 464
DrDavid Avatar asked Mar 11 '13 04:03

DrDavid


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do I search for a string with awk?

Using Awk with set [ character(s) ] Take for example the set [al1] , here awk will match all strings containing character a or l or 1 in a line in the file /etc/hosts.

What does $1 $2 indicate in awk file?

Awk works by scanning through each line of text (or record) in the file and carrying out any instructions you tell it on that line. In awk we access fields using syntax like: $1 or $2. $1 indicates that you are referring to the first field or first column.


1 Answers

One way:

awk -F: '$1=="Account number"{print $2;exit;}' file 

I assume you want to stop the moment you find the first occurence in the file. If you want to find occurrences in every line of the file, just remove the exit .

like image 182
Guru Avatar answered Oct 02 '22 01:10

Guru