简体   繁体   中英

Deleting lines containing specific words in text file in Ruby

I have a text file like this:

User accounts for \\AGGREP-1

-------------------------------------------------------------------------------
Administrator            users                    grzesieklocal
Guest                    scom                     SUPPORT_8855
The command completed successfully.

First line is empty line. I want to delete every empty lines in this file and every line containing words "User accounts for", "-------", "The command". I want to have only lines containing users. I don't want to delete only first 4 and the last one lines, because it can be more users in some systems and file will contain more lines. I load file using

a = IO.readlines("test.txt")

Is any way to delete lines containing specific words?

IO::readlines returns an array, so you could use Array#select to select just the lines you need. Bear in mind that this means that your whole input file will be in memory, which might be a problem, if the file is really large.

An alternative approach would be to use IO::foreach , which processes one line at a time:

selected_lines = []
IO.foreach('test.txt') { |line| selected_lines << line if line_matches_your_requirements }

Solution

This structure reads the file line by line, and write a new file directly :

def unwanted?(line)
  line.strip.empty? ||
    line.include?('User accounts') ||
    line.include?('-------------') ||
    line.include?('The command completed')
end

File.open('just_users.txt', 'w+') do |out|
  File.foreach('test.txt') do |line|
    out.puts line unless unwanted?(line)
  end
end

If you're familiar with regexp, you could use :

def unwanted?(line)
  line =~ /^(User accounts|------------|The command completed|\s*$)/
end

Warning from your code

The message warning: string literal in condition appears when you try to use :

string = "nothing"

if string.include? "a" or "b"
  puts "FOUND!"
end

It outputs :

parse_text.rb:16: warning: string literal in condition
FOUND!

Because it should be written :

string = 'nothing'

if string.include?('a') || string.include?('b')
  puts "FOUND!"
end

See this question for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM