Reputation: 43
I am trying to just put column 1 from the infile to the outfile but I am getting the whole line (outfile). How do I just put 1st column into the outfile?
Infile:
Game1_1000 2002.1111 1000.1111
Game2_20001 1111.2222 1122.2222
Game3_2222 1111.3333 1111.2221
Current Outfile: (not what I wanted)
baseball Game1_1000 2002.1111 1000.1111
baseball Game2_20001 1111.2222 1122.2222
baseball Game3_2222 1111.3333 1111.2221
I want the outfile to be like below:
baseball Game1_1000
baseball Game2_20001
baseball Game3_2222
Here is my script:
set infile [open "infile.txt" r]
set outfile [open "outfile.txt" w]
set lines [split [read -nonewline $infile] "\n"]
foreach line $lines {
puts $outfile "Baseball"
}
Upvotes: 1
Views: 587
Reputation: 137567
You have an input file where the individual lines are split into fields by sequences of whitespace. The split
command doesn't handle that; it splits on every space (there are other file formats where this is the right option). Because of that, we need a different step to condition the input line into records for processing.
There are various ways of doing this. My favourite is to use regexp
to select all non-whitespace sequences as words (it's got a nice short regular expression, the \S+
):
set columns [regexp -all -inline {\S+} $line]
Once that's been done, you should get what you ask for from the rest of the code as you write it.
More complex splitting is usually best left to the textutil::splitx
command from Tcllib. The case you describe in your question is how it splits things by default, making using it extremely easy.
package require textutil
set columns [textutil::splitx $line]
Upvotes: 1
Reputation: 71538
Your script cannot give the output you say you are getting in the current outfile, it should be generating a file with Baseball
only.
That aside, you could split the line on space and take the first element using lindex
:
set infile [open "infile.txt" r]
set outfile [open "outfile.txt" w]
set lines [split [read -nonewline $infile] "\n"]
foreach line $lines {
set columns [split $line " "]
puts $outfile "baseball [lindex $columns 0]"
}
close $infile
close $outfile
Upvotes: 2