Reputation: 7650
I got this data:
aaa:123 bbb:**234** ccc:345
eee:435 ddd:**231** xxx:897
...
How to get the bolded part by using Awk?
Upvotes: 3
Views: 7543
Reputation: 2520
You can use something like this
BEGIN { FS = ":" }
{
split($(NF-1),a," ");
$2=a[2];
print $2;
}
Supposed that your column is is always the 2th
and the number of columns is 3
.
Upvotes: 1
Reputation: 41446
I would have used this:
awk '{split($2,a,":");print a[2]}' file
Why? Its not easy to see if its space or tab that separates the filed. Using default setting of FS in awk is any blank, so it will work even if its tab or spaces. Then we from second field take out part we need, using split by :
Upvotes: 4
Reputation: 25032
A general approach to obtaining portions of fields is to use split
:
awk -F':' '{ split($3, subfield, " "); print subfield[1] }'
Others have mentioned using a regex to treat both spaces and colons as field separators. This is fine, so long as the number of spaces is predictable. But it will fail otherwise, e.g., for input like this:
aaa:123 bbb:234 ccc:345
eee:435 ddd:231 xxx:897
fff:214 ads 23423 fds:183 eee:234
Pick whichever approach better matches your data.
Upvotes: 16
Reputation: 123458
It's rather straightforward. Did you try
awk -F'[: ]' '{print $4}' inputfile
Upvotes: 3
Reputation: 36262
Use a regular expression of spaces plus colon and count fields:
awk -F'[[:blank:]:]+' '{ print $4 }' infile
It yields:
234
231
Upvotes: 6