Use “For Each” to replace texts

I've got three files:

File 1:PlaceHolder_for_Repalce.txt
Like this:
aaa
bbb
ccc
ddd

File 2: Wanted_Lines.txt
Like this:
1
2
3

File 3:
Already Open in Sublime Text App which contains "aaa", "bbb", "ccc" in the middle of other texts.

What I want to do is replace "aaa", "bbb", "ccc" to "1", "2", "3" in File 3.

But I end up replace "aaa", "bbb", "ccc" ALL to "1" using the macro below ↓

I've think about it for days and have no progress. Can anyone fix this?

Do you have to have the data separated into two files?
It would be much simpler, if you had all the data in one file, using this format:
<placeholder>,<replacement>

So it would look like

aaa,1
bbb,2
ccc,3

If any of your data uses a comma, then you can choose any character that you are not using, including a TAB character.

Let us know if this will work for you, and then I'll build an example macro for you.

It’s not a hard thing to form this style, I guess you’d use %Variable[1]%, %Variable[2]% to finish this job. Seems good~

If that means you are OK with my proposed format, please provide the following:

  1. Real-world example data set of the placeholder/replacements.
  2. Real-world example of the entire text in Atom editor.

Here it is~
Related_Files_2018-03-20_15-01.zip (4.4 KB)

Here's a barebones example macro that performs the find and replace directly in KM rather than in Sublime Text using the <placeholder>,<replacement> format (make sure to change the paths to the files to the appropriate ones on your own system):

[Example] Use For Each to Replace Text.kmmacros (2.9 KB)
29 PM

I'm sure that @JMichaelTX's example macro will be much more comprehensive and instructional than this, but in the meantime, hopefully this will get you started. If you have any questions, feel free to ask.

1 Like

That’s a clean, beautiful macro~ I love you guys and this forum~ Thanks! Regex is cool and I gotta do more homework about it :wink:

1 Like

Nope, you did a great job, @gglick. I don't see anything I would do different for small files.

If the target file to be changed is large, then it might be better to open the file once, get the contents, make all the changes, then write back out to the file, as opposed to opening/reading/changing/writing the file for each change.

1 Like