ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
my situation is following: I would like to use the for loop (not necessarily for loop) with awk command in such a way that awk doesn't evaluate first the first row through all the iterations of the loop, but to evaluate all the rows for the first iteration, then all the rows for the second iteration, and so on.
For example, if I have a file like
2 3
4 5
and I want to print $1,$2,$1*t,$2*t, for the values of t from 1 to 3, I would like to get
You'll need to read the input into an array, and do the output in a loop at end:
Code:
awk '{ line[NR] = $0 }
END { for (t = 1; t <= 3; t++)
for (i = 1; i <= NR; i++) {
printf("%s", line[i])
n = split(line[i], field)
for (k = 1; k <= n; k++)
printf(" %g", t * field[k])
printf("\n")
}
}' proba.dat > proba1.dat
There are different ways to perform a loop using awk. You can rewind the file to parse it multiple times, or you can pass the file name as argument multiple times. Some options are covered in this thread, see in particular post #2 and post #6. The suggestion by Nominal Animal is good, unless the file size is huge.
I would recommend using a tool that can seek and tell a file (Python|Perl|Ruby etc) . an example in Ruby
Code:
#!/usr/bin/env ruby
# Ruby1.9+
f=File.open('file')
1.upto(3) do |i|
while not f.eof
s = f.readline.split.map(&:to_i)
puts "#{s[0]} #{s[1]} #{s[0]*i} #{s[1]*i}"
end
f.pos = 0 # goes back to start of file...
end
f.close
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.