As easy as it might be to want to use vim
(or sed
for this), awk
is actually entirely capable of doing this type of matching and substitution all on its own:
$ awk '{ sub(/^.* - /, ""); sub(/,.*$/, ""); print $0 }' file
23499
The above matches everything (with awk
's built-in sub()
function) from the beginning of the line to the hyphen and space before the account number and replaces it with the empty string ""
. Then, it matches everything from the comma to the end of the line and replaces it with the empty string. This should robustly (e.g., regardless of how many emails or what their formatting might be) remove everything but the account number.
If you have access to gawk
, then you can use a simpler solution (only one function call needed):
$ gawk 'match($0, /^.* - ([0-9]+),.*$/, a) { print a[1] }' file
23499
Of course, the above solutions print the new data to stdout
. If you wanted to save the new data for use later, all you would need to do is add > newfile
to the end of the above command (note, that >
overwrites; if you would prefer appending, you can use >>
).
awk
has many limitations of its own (for example, working with many files at the same time), so it's not always the best tool for this type of manipulation. However, it is quite good at what it does, so when your use-case lines up with its round-house, I'd strongly recommend using it.
In addition, the above solution requires no interactive interface (like vim
) and no piping.