Issue
I have multiple bash code file, with 3-4 lines in each (like the following).
#!/bin/bash
echo "xy"
echo "x.com"
echo "z"
I want to have the output csv file like following (output of each file in a line of a csv file)
|name|sit|alternate_name
|:----|:----:|----|
|x|x.com|z
|y|y.com|f
but I'm getting the output like-
||
|:----:|
|x|
|x.com|
|z|
|y|
|y.com|
|f|
My code is as follows-
for i in $(ls script_B*)
do
./$i | awk -F ':' '{OFS=",";print $1,$2,$3}' >> output.csv
done
I'm a noob in this area and couldn't do much study on awk. Any help is appreciated.
Solution
You need to accumulate 3 lines of input before writing a line of output, something like
$ awk -F: 'BEGIN {OFS=","} NR % 3 == 1 {line1=$0} NR % 3 == 2 {line2=$0} NR % 3 == 0 { print line1, line2, $0 }' <<EOF
x
x.com
z
EOF
x,x.com,z
NR
is the number of the current input line (starting with 1). Compute the remainder modulo 3 tells you if you are on the first, second, or third line of an input group. If each awk
is only reading a single 3-line file, you can simplify that to
% awk -F: 'BEGIN {OFS=","} NR == 1 {line1=$0} NR == 2 {line2=$0} NR == 3 { print line1, line2, $0 }' <<EOF
x
x.com
z
EOF
x,x.com,z
In the first two cases, you have to remember the current line with a variable until awk
reads the last line; I'm not aware of a version of awk
that allows you to consume more lines of input within a single action.
Answered By - chepner