Sachin Shinde
Sachin Shinde

Reputation: 39

Creating files as per the column pattern

I want to create files as per the first column value, suppose I have ASCII data in the file, which contains..

400.00     1234
400.00     2134
400.05     4314
400.05     9766
401.00     9874
401.00     7982
402.50     1234

Now I want to write a shell or awk script which creates a file which has a name as "Timestep_401.00" and contains only records belonging to that column value i.e it should contains....

401.00    9874
401.00    7982

I was trying with the script as below..

awk '{ if($1=401.00) {print >> "Timestep_"$1; close($1)}}' awk.txt

But it is providing wrong output (though Timestep_400 file is get created as a output) as it contains all the data from the file. Just the value of first column and all records from the second column of the input file. Content of Timestep_400 file

401.00     1234
401.00     2134
401.00     4314
401.00     9766
401.00     9874
401.00     7982
401.00     1234

Upvotes: 0

Views: 24

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74645

It looks like the main thing wrong with your script is a typo: = is an assignment, not a comparison.

Personally I'd use a string comparison, to avoid having to think about issues related to floating point values (and because awk sees the fields as strings anyway).

I'd also lose the unnecessary if because awk scripts work like condition { action }.

awk '$1 == "401.00" { print > ("Timestamp_"$1) }' awk.txt

I'm guessing that you want to use > instead of >>. > means "open and truncate the file" but on subsequent lines, the file is already open, so it will be appended to. If Timestamp_401.00 already exists before you run the script and you to preserve its contents, use >> as you were doing.

I guess you meant to close the file that you had just written to but it's not necessary to do this once per line - in fact, this would mean that > reopened (and truncated) the file every time the block is executed.

Upvotes: 1

Related Questions