Community discussions

MikroTik App
 
nriedman
just joined
Topic Author
Posts: 22
Joined: Mon Feb 17, 2014 9:31 pm

Foreach iterate through each line in a txt file

Wed Jan 14, 2015 9:05 pm

Sorry for my ignorance, but I am trying to run a for loop through each line in a text file. What I am finding is that mikrotik doesn't recognize a new line or carriage return and therefore treats the entire file as one string. Is there a way to do this? I have included the command below:

foreach i in=[/file get test.txt contents] do={/ip firewall address-list add list=zone address=$i}
 
User avatar
skot
Long time Member
Long time Member
Posts: 584
Joined: Wed Nov 30, 2011 3:05 am

Re: Foreach iterate through each line in a txt file

Thu Jan 15, 2015 6:43 pm

You can do this by checking for line endings "\n" (linux)or "\r\n" (windows). Something like this:
{
:local content [/file get [/file find name=file.txt] contents] ;
:local contentLen [:len $content];

:local lineEnd 0;
:local line "";
:local lastEnd 0;

:while ($lineEnd < $contentLen) do={
# depending on file type (linux/windows), "\n" might need to be "\r\n"
	:set lineEnd [:find $content "\n" $lastEnd];
# if there are no more line breaks, set this to be the last one
	:if ([:len $lineEnd] = 0) do={
		:set lineEnd $contentLen;
	}
# get the current line based on the last line break and next one
	:set line [:pick $content $lastEnd $lineEnd];
# depending on "\n" or "\r\n", this will be 1 or 2 accordingly
	:set lastEnd ($lineEnd + 1);
# don't process blank lines
	:if ($line != "\r") do={
		/ip firewall address-list add list=zone address=$line
	}
} 
}
 
Wyz4k
Member Candidate
Member Candidate
Posts: 240
Joined: Fri Jul 10, 2009 10:23 am

Re: Foreach iterate through each line in a txt file

Thu Aug 27, 2020 6:05 am

/file get [/file find name=file.txt] contents - has a known limitation of 4095 bytes. So if the file you are trying to read is larger than that it will fail. Ridiculous I know.

Who is online

Users browsing this forum: No registered users and 36 guests