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

The accepted answer outputs a space in front of the string which forced me to use another approach:

awk '/Account number/{print $3; exit}'

This solution ignores the : separator but works like a charm and is a bit easier to remember IMO.


You can use an if to check if $1 and $2 equal "Account" and "number:". If they do, then print $3:

> awk '{if ($1 == "Account" && $2 == "number:") {print $3; exit;}}' input.txt

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 .

Tags:

Bash

Awk