Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print array elements

Status
Not open for further replies.

ranjit

Technical User
Apr 14, 2000
131
GB
I have the below code which prints the elements of an array delimited by a ":" terminating in a new line.

The code is somewhat unwieldy - is it possible to find a more succinct way of doing this?

cat data.tmp |awk '
BEGIN { OFS=":" }
{ split($0,A,",") }

{
if (A[8] ~/trunk_priority=/) {
printf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", A[1],OFS,A[2],OFS,A[4],OFS,A[5],OFS,A[6],OFS,A[7],OFS,A[8],OFS,A[9],OFS,A[10],OFS,A[11],OFS,A[12])
}
else {
printf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", A[1],OFS,A[2],OFS,A[4],OFS,A[5],OFS,A[6],OFS,A[7],OFS,A[8],OFS,A[9],OFS,A[10],OFS,A[11])
}
} ' >output

thanks,
 
Hi

Use a [tt]function[/tt] ?
Code:
cat data.tmp |awk '
BEGIN { OFS=":" }
{ split($0,A,",") }

{
if (A[8] ~/trunk_priority=/) {
[red]printElem(A,"1,2,4,5,6,7,8,9,10,11,12")[/red]
}
else {
[red]printElem(A,"1,2,4,5,6,7,8,9,10,11")[/red]
}
}
[red]function printElem(arr,elem){n=split(elem,e,",");for(i=1;i<=n;i++)printf"%s%s",arr[e[i]],OFS;print""}[/red]
' >output
Or you can pass the separators too in parameters to the [tt]function[/tt], eventually with default values so they can be ignored :
Code:
function printElem(arr,elem,sep,end)
{
  if (!sep) sep=OFS
  if (!end) end=ORS
  n=split(elem,e,",")
  for (i=1;i<=n;i++) printf "%s%s",arr[e[i]],sep
  printf "%s",end
}
Or just choose the simple way : ;-)
Code:
cat data.tmp |awk '
BEGIN { OFS=":" }
{ split($0,A,",") }

{
if (A[8] ~/trunk_priority=/) {
[red]print A[1],A[2],A[4],A[5],A[6],A[7],A[8],A[9],A[10],A[11],A[12][/red]
}
else {
[red]print A[1],A[2],A[4],A[5],A[6],A[7],A[8],A[9],A[10],A[11][/red]
}
} ' >output

Feherke.
 
Many thanks Feherke for your assistance. I think i'll go for the "simple way" - improves readability considerably.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top