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


File.open(filename).each do |line|
  puts line.split('|')[14]
end

      



must do the trick.

+4


source


You don't need ruby ​​for this.

echo "aaa,bbb,ccc" | cut -d ',' -f 2
# bbb

      

If you choose to use ruby, you can split the line like this:



"aaa,bbb,ccc".split(",")[1]
# bbb

      

You can also check stdlib CSV . See Parameter :col_sep

.

0


source


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







All Articles