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!

skipping first line error 1

Status
Not open for further replies.

ggg777

Programmer
May 11, 2009
1
US
Hi all,

I have the following script to read the second columns of each line and printing those columns to the separate files such as 1.txt, 2.txt etc.

value = 1;
BEGIN { RS = "\n" } ;
{
while(getline > 0){
filename = (value ".txt");
print $2 >> filename;
value = value + 1;
}
}

However, this script always skips the first line for the following file content if I don't put a empty line at the very beginning (but I don;t wanna do that). How can I fix this problem? Thank you very much.

vidWos6D 0
GCYlRuPA 355
rDLWdHPV 128
RH8ucXOb 552
qCUtKgfd 380
 

There seems to be no stated purpose to what you want to achieve, maybe if you better describe the issue you need to resolve and the requirements you need to meet, we can help you find a better solution.

- Post sample of source data
- Post exepected result.

[3eyes]


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
The main body of an awk program is run for every input line, so it figures that your program skips the first line.

value = 1; [red]<= this statement should be in BEGIN section[/red]
BEGIN { RS = "\n" } ; [red]<= newline as record separator, I should think that is the default behaviour and semicolon after the BEGIN block is not needed[/red]
{
while(getline > 0){ [red]<= first iteration of getline loop overwrites first record which was already read[/red]
filename = (value ".txt");
print $2 >> filename;
value = value + 1;
}
}

So I'd try this:
[tt]
BEGIN {
value = 1
}
{
filename = (value ".txt");
print $2 >> filename;
value = value + 1;
}
[/tt]


HTH,

p5wizard
 
And even shorter: (use increment operator and increment before use, so you don't need to preset value to 1 - not even to 0 because that is done automatically; brackets are optional - conversion to string and concatenation is done before assignment - and semicolons at end of line are not needed)

[tt]
{
value++
filename=value ".txt"
print $2 >> filename
}
[/tt]

You can even leave out some of the spaces and newlines (if you put in the semicolons again) to make the awk program into a oneliner but that only makes it more difficult to read and understand.

[tt]
{value++;filename=value".txt";print $2>>filename}
[/tt]


HTH,

p5wizard
 
What about this ?
{print $2>>(++value)".txt"}

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top