I have a table with many rows and a variable number of columns per row.
In each row, I only want to print the first field and all the fields containing one of two strings (in this example, I want all fields containing the words dog and cow).
For example:
A dog999 dog284 cow284 pig383 pig234 cow432 chicken432
B cow394 cow432 cow345 dog983 pig345 chicken532
C dog847 pig357 pig236 cow395 dog496
D dog392 cow237 cow749
Desired output:
A dog999 dog284 cow284 cow432
B cow394 cow432 cow345 dog983
C dog847 cow395 dog496
D dog392 cow237 cow749
So far with awk I have:
awk -v OFS='\t' '{for (i = 1; i <= NF; i++) {if ($i ~ /dog/) print $1,$i; else if ($i ~ /cow/) print $1,$i} }' file.txt
But that results in one line for every field that contains one of those two strings.
printf
instead of print and addprint ""
outside of your loop.