If I am searching for AA then then BB in a loop, how do I make the output always contain 6 columns of comma separated data even when there may only be 4 search matches?
AA11
AA12
AA13
AA14
BB11
BB12
BB13
BB14
BB15
BB16
Final output:
AA11,AA12,AA13,AA14,,,
BB11,BB12,BB13,BB14,BB15,BB16
Thanks for any help!
Just to clarify, you definitely want 6 columns, not 7.
Your output for the AA?? implies 7 columns...
Your output for the BB?? is 6...
A loop in what? Shell script, awk program, etc?
I need 6 columns regardless of the search results using a UNIX Bash Shell script.
---------- Post updated at 09:46 AM ---------- Previous update was at 09:46 AM ----------
Thanks in advance!
RudiC
June 2, 2014, 9:57am
5
Try this:
awk ' {TMP=substr($1,1,2)}
NR>1 && LAST!=TMP {printf "%s", PR
while (CNT++ < 6) printf ","
printf "\n"
PR=DEL=""; CNT=0}
{PR=PR DEL $0; DEL=","; CNT++; LAST=TMP}
END {print PR}
' file
AA11,AA12,AA13,AA14,,
BB11,BB12,BB13,BB14,BB15,BB16
What about 7 elements?
1 Like
Sorry about that, I made a typo, I only needed 6. Let me give this a try! Thanks
awk 'BEGIN {OFS = ","; n = 1}
NR == 1 {T = $0;
gsub(/[0-9]/, X);
A[n++] = T;
P = $0;
next}
{T = $0;
gsub(/[0-9]/, X);
if(P == $0 && n <=6)
{A[n++] = T}
else if (P != $0)
{print A[1], A[2], A[3], A[4], A[5], A[6];
n = 1;
split("", A);
A[n++] = T;
P = $0}}
END {print A[1], A[2], A[3], A[4], A[5], A[6];}' file
Thanks RudiC, the awk command worked just fine!
---------- Post updated at 11:08 AM ---------- Previous update was at 10:51 AM ----------
RudCi,
I did find a little glitch, if the last line of data is under 6, then the command does not put the require commas into the output to come up with six columns.
RudiC
June 2, 2014, 11:33am
9
Use
printf "%s", PR
while (CNT++ < 6) printf ","
printf "\n"
in the END section as well...
Another approach (a bit too long for one line)
awk '{n=substr($1,1,2); c=$0} n!=p{if(p){$0=s; s=x; $f=$f; print} p=n} {s=s c FS} END{$0=s; $f=$f; print}' f=6 OFS=, file
rudic:
Use
printf "%s", PR
while (CNT++ < 6) printf ","
printf "\n"
in the END section as well...
I am sorry, I cannot figure out how this is supposed to be added into the original command
---------- Post updated at 04:27 PM ---------- Previous update was at 04:25 PM ----------
scrutinizer:
Another approach (a bit too long for one line)
awk '{n=substr($1,1,2); c=$0} n!=p{if(p){$0=s; s=x; $f=$f; print} p=n} {s=s c FS} END{$0=s; $f=$f; print}' f=6 OFS=, file
I cannot make this work, it error-ed out.
What error did you get? What is your OS and version?
1 Like
RudiC
June 3, 2014, 5:04am
13
Instead of END {print PR}
use
END {printf "%s", PR
while (CNT++ < 6) printf ","
printf "\n"}
1 Like
Thanks, that worked!
---------- Post updated at 07:49 AM ---------- Previous update was at 07:41 AM ----------
I am on a SunOS 5.10 at a Bash prompt. The awk man page does not tell me the version of awk.
On Solaris use /usr/xpg4/bin/awk rather than awk