How to use ruby ββto extract a field
I am trying to write a ruby ββprogram that will open a file, extract the 15th field highlighted "|"
, and print that to the screen. I need to test it by doing the following (example):
cat /directory name/directory name/filename.rrf | less
and the 15th field of each line of this file will appear on the screen. Any help would be appreciated.
+3
source to share
3 answers
Assuming you are using Unix line breaks ( \n
), do the following:
file = File.open("data", "r") # input filename goes here
data = file.read
file.close
lines = data.split(/\n/)
lines.each { |line|
p line.split(/\|/)[14]
}
For simplicity, the above code does not check if there are at least 15 fields on each line.
0
source to share