Page 1 of 1

Find selection in workspace files

Posted: Fri Jun 01, 2007 1:43 am
by lotus298
This perl script will parse a TWS workspace for a list of files you have open, and search each file for the selected text.

Remember to save your workspace before running this, as it parses the last saved workspace. Anyone know if "save workspace" is macro-able?

This works great with version 5's auto-hide command output mode.

Code: Select all

# DOS command should be:
#    perl c:\userdata\temp\textpad\findinfiles.pl "$WspDir\$WspBaseName.tws" "$Sel"
# Regex should be:
#    ^([0-9]+):.*thefilenameis(.+)$
#    Line is \1
#    File is \2


my $twsfilename = $ARGV[0];
my $selection = $ARGV[1];

open (INFILE, "<$twsfilename") || die "Failed to open $twsfilename";
my @twslines = (<INFILE>);
close INFILE;

if ($selection eq "") {
  print "Selection is empty.\n";
  exit 0;
} else {
  print "Searching for \"$selection\"\n";
}

my @filenames = ();

foreach (@twslines) {
  split(/ECOD../, $_);
  foreach (@_) {
    if ($_ =~ /^(.+?)\x01/gi) {
      @filenames = (@filenames, $1);
    }
  }
}

foreach $filename (sort @filenames) {

  open (INFILE, "<$filename") || next;
  my @lines = (<INFILE>);
  close INFILE;

  print "\n$filename\n";
  my $linenum = 1;
  foreach $line (@lines) {
    chomp $line;
    if ( $line =~ /${selection}/gi ) {
      my $tmp = sprintf( "%03u", $linenum );
      print "$tmp:  $line \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t thefilenameis$filename\n";
    }
    $linenum = $linenum + 1;
  }

}

Posted: Fri Jun 01, 2007 3:31 pm
by ben_josephs
Thanks very much for that. It's most useful. I'm already using two scripts based on it: one to search within files in the current workspace, the other, for use on the command line, to list the filenames of documents in a workspace.

Re: Find selection in workspace files

Posted: Fri Jun 01, 2007 5:41 pm
by lotus298
You can make it work for the active workspace by changing the command to:

perl c:\userdata\temp\textpad\filecompare.pl "$WspDir\$WspBaseName.tws" "$File"

It's amazing what you find when you read the help pages...