logeeks
logeeks

Reputation: 4979

replacing number at a particular point in text file

I have a text file with following content(content is variable to >10 MB) I want to set/replace the copies count to a dynamic number and. I have used sed utiliy to do the same but it will show comand prompt. Is there any way using C#/regular expression?

How can i write the changed patterns back into file?

%-12345X@PJL JOB NAME = "Microsoft Word -Values.docx"
@PJL OKIAUXJOBINFO DATA="ComputerName=USER-PC"
@PJL OKIAUXJOBINFO DATA="UserName=user"
@PJL OKIAUXJOBINFO DATA="PortName=PORTCUSTOM"
@PJL OKIAUXJOBINFO DATA="ReceptionTime=22:04:09 2012/02/01"
@PJL OKIAUXJOBINFO DATA="DocumentName=Microsoft Word - LDAPValues.docx"
@PJL OKIAUXJOBINFO DATA="MultiPage=1"
@PJL OKIAUXJOBINFO DATA="ApplicationName=Microsoft Office Word"
@PJL OKIJOBACCOUNTJOB JOBACCOUNTID=0 USERID="user" JOBNAME="Microsoft Word - Values.docx"
@PJL RDYMSG DISPLAY = ""
@PJL COMMENT OS Version   : Windows NT 6.1 Build 7600 
@PJL COMMENT Product Name : OKI PCL5c Printer Driver
@PJL COMMENT Device Name  : OKI
@PJL COMMENT Version      : 1.0.5
@PJL COMMENT Build Date   : 2010/03/30 (Tue) 16:17:01
@PJL SET OKIPAPERSIZECHECK=ENABLE
@PJL SET OKICUPAPERSIZECHECK=ENABLE
@PJL SET MANUALFEED=OFF
@PJL SET OKIXDIMENSIONMILLIMETER=216
@PJL SET OKIYDIMENSIONMILLIMETER=280
@PJL SET MEDIASRCMANUAL=2
@PJL SET MEDIASRCINTRAY1=4
@PJL SET MEDIASRCINTRAY2=1
@PJL SET MEDIASRCINTRAY3=5
@PJL SET MEDIASRCINTRAY4=6
@PJL SET MEDIASRCINTRAY5=20
@PJL SET MEDIASRCINTRAY6=21
@PJL SET MEDIASRCINTRAY7=22
@PJL SET QTY=1
@PJL SET COPIES=2
@PJL SET OKIRESOLUTION=X600Y600LEVEL2

Upvotes: 0

Views: 328

Answers (2)

David Merriman
David Merriman

Reputation: 6086

Seems like

Regex.Replace(
    input, 
    @"COPIES=\d+", 
    string.Format("COPIES={0}", number), 
    RegexOptions.Multiline);

would do the trick.

http://msdn.microsoft.com/en-us/library/taz3ak2f.aspx

Writing it back into the file will look something like this:

string input = File.ReadAllText("filename.txt");
string output = Regex.Replace(
    input, 
    @"COPIES=\d+", 
    string.Format("COPIES={0}", number), 
    RegexOptions.Multiline);
File.WriteAllText("filename.txt", output);

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

This finds the number after "@PJL SET COPIES="

(?<=@PJL\ SET\ COPIES=)\d+

Use it like this

Regex.Replace(text, @"(?<=@PJL\ SET\ COPIES=)\d+", newCount.ToString());   

I used the Regex lookaround pattern

(?<=prefix)find

Upvotes: 3

Related Questions