Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching file for a set of strings

Status
Not open for further replies.

kirk124

Programmer
Apr 15, 2003
26
US
Hi, I want to find out if a file contain the following strings:

set CMP_DATA_INBND_DIR=C:\h\csscs\data\commi\tmp_queue
set CMP_DATA_OUTBND_DIR=C:\h\CMP\data\outbound
set JAVA_HOME=C:\h\COTS\JAVA2\1.3
set CSSCS_DATA=C:\h\csscs\data

and if not to add them to the file. So if the first three strings exist but not the fourth then add the fourth string. I was thinking that this might need a hash. What do you thinks? --thanks
 
Code:
use strict;
use warnings;

#escape the backslashes
my @list = ('set CMP_DATA_INBND_DIR=C:\\h\\csscs\\data\\commi\\tmp_queue',
			'set CMP_DATA_OUTBND_DIR=C:\\h\\CMP\\data\\outbound',
			'set JAVA_HOME=C:\\h\\COTS\\JAVA2\\1.3',
			'set CSSCS_DATA=C:\\h\\csscs\\data');

#open the file for both reading and writing, without truncating the file
open FILE, &quot;+<file.to.search.txt&quot; or die $!;

#for each item to search for
foreach my $item (@list)
{
	my $found = 0;
	#look thru the file, line by line
	while(<FILE>)
	{
		#everything between \Q and \E are taken as literal characters, like backslashes
		if(/\Q$item\E/)
		{
			#if found, set so and break
			$found = 1;
			last;
		}
	}
	unless($found)
	{
		#seek to end of file, though should already be there
		#I read that it's good to seek before writing, anyway
		seek FILE, 0, 2;
		#speaking of writing, here goes
		print FILE $item;
	}
	#seek back to the beginning of the file, and loop again
	seek FILE, 0, 0;
}
close FILE;

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top