# Processing a text file

**URL:** <https://www.ruby-forum.com/t/processing-a-text-file/85735>\
**Category:** Ruby\
**Created:** [February 15, 2007, 10:55pm UTC](https://www.ruby-forum.com/t/processing-a-text-file/85735 "2007-02-15T22:55:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![barjunk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@barjunk](https://www.ruby-forum.com/u/barjunk)\
**Post date:** [February 15, 2007, 10:55pm UTC](https://www.ruby-forum.com/t/processing-a-text-file/85735/1 "2007-02-15T22:55:19Z")

</div>

I have a radius users text file that has entries like:

# username - Thu Feb 15 08:59:03 AKST 2007

davidh Calling-Station-Id != “00-1A-02-3E-93-28”, Auth-Type := Reject  
davidh User-Password == “secretpass”

# 

There are two things I would like to be able to do separately, one is  
to delete that set of lines given the username.

The second is to change the password or the MAC address given the  
username.

I think the second one is probably easy, using regex some sort of  
“sed” like command.

The first one is a little more demanding on my nuby mind. I guess I  
can figure out some sort of “grep -v” functionality, but that leaves  
the line above and below as cruft.

Suggestions?

Mike B.

---

<div class="post-metadata">

**Author:** ![barjunk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@barjunk](https://www.ruby-forum.com/u/barjunk)\
**Post date:** [February 16, 2007, 6:18am UTC](https://www.ruby-forum.com/t/processing-a-text-file/85735/2 "2007-02-16T06:18:42Z")

</div>

barjunk wrote:

> I have a radius users text file that has entries like:
> 
> # username - Thu Feb 15 08:59:03 AKST 2007
> 
> davidh Calling-Station-Id != “00-1A-02-3E-93-28”, Auth-Type := Reject  
> davidh User-Password == “secretpass”
> 
> #

…

I don’t know how big the file is, but if you can read it all into a  
string (e.g. str = File.read(“the\_file”) ), you could use something like  
this:

def zap\_unwanted\_lines(str, user)  
re = %r[  
^#\s+username\s±\s+\w{3}\s\w{3}\s\d{2}\s\d{2}:\d{2}:\d{2}\s\w+\s\d{4}\n  
#{user}\s+Calling-Station-Id[^\n]+\n  
#{user}\s+User-Password[^\n]+\n  
#\s\*\n  
]x

str.gsub re, ‘’  
end

TEXT = %q{

# username - Thu Feb 15 08:59:03 AKST 2007

davidh Calling-Station-Id != “00-1A-02-3E-93-28”, Auth-Type := Reject  
davidh User-Password == “secretpass”

# 

}

dummy = “This is some dummy text\n” \* 5  
fake\_radius\_data = dummy + TEXT + dummy + TEXT + dummy

puts “— Before zapping —”  
puts fake\_radius\_data  
puts “— After zapping —”  
puts zap\_unwanted\_lines(fake\_radius\_data, “davidh”)
