Issue
I want to get multiple words from CSV file and combine forward sentence. Awk command is very useful. But this is not expectation. Is there any way to solve this problem?
command:
awk -F , '{ #process to csv file
for(i=1;i<=NF;i++) #process to every row
{if($i~/bbb|ccc/) #if find bbb or ccc
{print $1","$2","$i}} #print column1 and column2 and bbb and ccc
}'
CSV file content:
r1c1,r1c2,bbb,
r2c1,r2c2,bbb,ccc
r3c1,r3c2,xxx,yyy
↓
output:
r1c1,r1c2,bbb,
r2c1,r2c2,bbb
r2c1,r2c2,ccc
expectation:
r1c1,r1c2,bbb,
r2c1,r2c2,bbb,ccc
r1c1 is row1 and col1, r1c2 is row1 and col2. xxx,yyy is not contained bbb or ccc, so this is not displayed.
Solution
You may use this awk
:
awk -F, '{
s = $1 FS $2
for (i=3; i<=NF; ++i)
if ($i ~ /^(bbb|ccc)$/) {
s = s FS $i
ok = 1
}
if (ok) print s
ok = 0
}' file
r1c1,r1c2,bbb
r2c1,r2c2,bbb,ccc
Answered By - anubhava Answer Checked By - Marie Seifert (WPSolving Admin)