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!

Conversion

Status
Not open for further replies.

userand

Technical User
Apr 12, 2011
28
CH
Hello,

I have the following output from some program:

10 3 7 9 10

the first column is: there should be 10 colums
the other columns are the position of some arbitrary character, let's say "1". I need to convert the row above to this line

0 0 1 0 0 0 1 0 1 1

Could anyone help me?
 
Hi

This is very similar to your question in thread271-1665873. Have you tried to solve this yourself ?


Feherke.
 
Yes, I have already tried it, but this case is a bit different, because I have only one row and just the positions of the "1"-s...
 
Hi

Next time I will way until you show some proof of your own efforts.
Code:
awk '[teal]{[/teal][b]for[/b][teal]([/teal]i[teal]=[/teal][purple]1[/purple][teal];[/teal]i[teal]<=[/teal][navy]$1[/navy][teal];[/teal]i[teal]++)[/teal]a[teal][[/teal][navy]$i[/navy][teal]]=[/teal][purple]1[/purple][teal];[/teal][b]for[/b][teal]([/teal]i[teal]=[/teal][purple]1[/purple][teal];[/teal]i[teal]<=[/teal][navy]$1[/navy][teal];[/teal]i[teal]++)[/teal][COLOR=chocolate]printf[/color][green][i]"%s%s"[/i][/green][teal],[/teal]a[teal][[/teal]i[teal]]||[/teal][purple]0[/purple][teal],[/teal]i[teal]<[/teal][navy]$1[/navy][teal]?[/teal][blue]OFS[/blue][teal]:[/teal][blue]ORS[/blue][teal]}[/teal]' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].


Feherke.
 
Ok, thanks.

Just one more thing: could you suggest something to do this in a reverse mode, i.e. if I have only

0 1 0 0 1 0 1 1 1 0 1 0 1

rows, how could I convert these to one just contatining the positions of the "1"-s ?
(Probably it is not so easy when the number of columns might varied...)
 
IMHO. the first for-loop should run from i=2 to NF i.e it shoud be:
Code:
  for(i=2;i<=NF;i++)
    a[$i]=1;
Because when it runs from i=1 then it sets everytime the last array element to 1 (in this case 10th), so example for original line
Code:
10 3 7 8 9
it delivers the result
Code:
0 0 1 0 0 0 1 1 1 1
which is wrong.
It should be
Code:
0 0 1 0 0 0 1 1 1 0

 
Hi

Oops. Good catch, mikrom. Thank you.

( I actually had i=2 in a first version. But seems that I changed it accidentally while I rewrote it to optimize... )


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top