How to trim out extra CRLFs when parsing a text file?

Hello, my script converts columns in a row from a text file into an array. The problem starts if there is some extra enter characters at (in general) the end of text document. The enter chars are causing empty string error but I do not know how to check if an array has no elements.

I thought this may work first;

if (columns[0].length!=0) do_something

Bu later I realized it cannot check that because there is no [0] element either. My code continues on condition “if array is not empty”. I appreciate any opinions.

You shouldn’t check the length of the first element (which doesn’t exist), but the length of the array:

if (columns.length > 0) do_something
1 Like

Thank you, the answer is obvious :slight_smile: . Actually, I tried the same but with a mistake…

if (columns.length[i] > 0.....

@imagejan, Apparently, my ordeal with this one is not yet over :slight_smile:

This is the test.txt file contents, there are 3 enters at the end (not visible here):

one 0
two 0
three 0
four 0
five 0

Here is the code:

filestring=File.openAsString("C:\\Users\\Win10HoMe\\Desktop\\test.txt");
rows=split(filestring, "\n");
x1=newArray(rows.length); 
errorFlag=0;
for(i=0; i<rows.length; i++){
	columns=split(rows[i]," ");

			if (columns.length > 0){
				
				//check if its a string
				if (isNaN(parseFloat(columns[0]))){
	x1[i]=columns[0];
	print("current label is:"+x1[i]);
			}
			else errorFlag=1;//do something
			}
			}

Array.print(x1);

And this is the Log output;

current label is:one
current label is:two
current label is:three
current label is:four
current label is:five
one, two, three, four, five, 0, 0

When I view text file with hex viewer, the file ends with “0D 0A 0D 0A 0D 0A”

And no matter what, I just cant get rid of this extra enters…

You’re creating an array that has as many entries as there are rows. Unset entries will show up as 0 at the end.

To avoid this you can create an empty array first, and then add entries using the Array.concat macro function:

x1 = newArray();

    // in the loop
    x1 = Array.concat(x1, columns[0]);
1 Like

Perfect, thank you! The solution I found was detecting==firstzero and trimming from there since never thought of using concat.