Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Mindcrime

macrumors regular
Original poster
Oct 24, 2003
135
46
Houston, Texas
I'm new to programming anything and while I can find my way around the CLI and Terminal, I have no idea how to do the following:

Use a comma-delimited text file of terms (A,B) to replace all the A-terms in a folder of TXT files with the B-terms.

For example, if my comma-delimited text file has:

A,B
Foo,foobar
Fod,fodder
Fog,fogger

and then I have a folder of 10 .txt files that contain the A words, is there some kind of script that will go through the comma-delimited file, locate all instances of words from the A column in that folder of 10 text files and then replace them with the contents of the B column?

Thanks for any help!
 

pallit

macrumors newbie
Sep 19, 2005
4
0
Find/Replace

The quickest way I can think of is this:

perl -pi -e 's/find text/replace text/g' *.txt

This will go through all txt files in the current folder and replace "find text" with "replace text"

Pall
 

pallit

macrumors newbie
Sep 19, 2005
4
0
find/replace

This'll probably handle the whole thing for you:

#!/usr/bin/perl

$filename = "name of comma-delimited file";

open(FILE, "<$filename");
while(<FILE>){
chomp($_);
@myWords = split(/,/, $_);
$doIt = `perl -pi -e 's/$myWords[0]/$myWords[1]/g' *.txt`;
}

save it as findrep.pl in a folder along with all your .txt files and the delimited file and run it with: perl findrep.pl
backup all your files first, I didn't test it at all.

Pall
 

pallit

macrumors newbie
Sep 19, 2005
4
0
First of all, make sure your tab delimited file isn't a .txt file or it will get changed as well. give it a .text suffix instead. Also, there seems to be some weird formatting in your tab delimited file and the script isn't looping because of it. If you open the file with pico in the terminal 'pico skills.text' move down to the beginning of the second line, hit delete and return and then ctrl-x to quit (confirming the save). That seems to fix it.

Pall
 

Mindcrime

macrumors regular
Original poster
Oct 24, 2003
135
46
Houston, Texas
That did the trick - it seemed to work, tho when the script finished it gave me the following error:

sh: -c: line 1: unexpected EOF while looking for matching `''
sh: -c: line 2: syntax error: unexpected end of file

Does that mean anything serious?

Otherwise, thanks a ton for your help. You just saved me hours of editing work on this video game project :) I owe you big time.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.