Tuesday 9 January 2018

linux - Check variables from different lines with awk

itemprop="text">

I want to combine values from multiple
lines with different lengths using awk into one line if they match. In the following
sample match values for first field,

aggregating values from
second field into a list.



Input, sample
csv:



222;a;DB;a
222;b;DB;a
555;f;DB;a
4444;a;DB;a
4444;d;DB;a
4444;z;DB;a



Output:



222;a|b
555;f
4444;a|d|z


How
can I write an awk expression (maybe some other shell expression) to check if the first
field value match with the next/previous line, and then print a list of second fields
values aggregated and separated by a pipe?




Answer




awk '
BEGIN
{FS=";"}
{ if ($1==prev) {sec=sec "|" $2; }
else { if (prev) {
print prev ";" sec; };
prev=$1; sec=$2; }}
END { if (prev) { print
prev ";" sec;
}}'


This, as you
requested, checks the consecutive lines.




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...