AWK output to delimited string

The following

awk/\-0.81/ { print $0 }' fullYearData.txt

finds instances successfully

-0.81

In a long list of strings like:

2017-01-10 16:58   0.90 feet  Low Tide
2017-01-10 22:54   2.10 feet  High Tide
2017-01-11 07:19  -0.81 feet  Low Tide
2017-01-11 14:15   1.06 feet  High Tide
2017-01-11 17:48   0.89 feet  Low Tide
2017-01-11 23:42   2.13 feet  High Tide
2017-01-12 08:03  -0.81 feet  Low Tide
2017-01-12 14:51   1.06 feet  High Tide

      

Output:

2017-01-11 07:19  -0.81 feet  Low Tide
2017-01-12 08:03  -0.81 feet  Low Tide

      

How would I manage to output the result (2 lines in this case) on one line like:

2017-01-11 07:19  -0.81 feet  Low Tide, 2017-01-12 08:03  -0.81 feet  Low Tide

      

+3


source to share


5 answers


Another option is to introduce a field separator variable f

that is set after the first match.

awk '/-0.81/{s=s f $0; f=", "} END{print s}' fullYearData.txt

      



Initially both variables s

, and f

will contain an empty string ( "").

+3


source


$ awk '/-0.81/{if(!a)a=$0; else a=a", "$0} END{print a}' fullYearData.txt
2017-01-11 07:19  -0.81 feet  Low Tide, 2017-01-12 08:03  -0.81 feet  Low Tide

      

Or even shorter:



awk '/-0.81/{a=!a ? $0 : a", "$0} END{print a}' fullYearData.txt

      

Append the appropriate lines to variable ( a

) and in END

, print the variable a

. a

Would initially be zero, and validation if-else

was used to decide when to add ,

(i.e., not the first time, but add ,

for subsequent rows matched by the pattern.

+2


source


Another awk solution

awk 'BEGIN{old_ORS=ORS;ORS=", "}/-0.81/{print}END{ORS=old_ORS;print}' fullYearData.txt

      

+1


source


The buffer is output to b

and printed to END

:

$ awk '/-0.81/{b=b (b==""?"":", ") $0}END{print b}' file
2017-01-11 07:19  -0.81 feet  Low Tide, 2017-01-12 08:03  -0.81 feet  Low Tide

      

+1


source


just print the filter line without CR / LF (with "," after first occurrence, hardest part here)

awk '/-0.81/{printf( "%s%s", ! a++ ? "" : ", ", $0)}' YourFile

# with final new line if needed
awk '/-0.81/{printf( "%s%s", ! a++ ? "" : ", ", $0)}END{print}' YourFile

      

+1


source







All Articles