How to Read Lines from File into Array

Read lines from a file into a Bash array

Latest revision based on comment from BinaryZebra's comment
and tested here. The addition of command eval allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.

Use $IFS that has no spaces\tabs, just newlines/CR

$ IFS=$'\r\n' GLOBIGNORE='*' command eval  'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync

Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes "" and braces {} as in the example above


Edit:

Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around

With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)

Other notes:

Can also follow drizzt's suggestion below and replace a forked subshell+cat with

$(</etc/passwd)

The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this

Reading a file line by line into elements of an array in Python

testsite_array = []
with open('topsites.txt') as my_file:
for line in my_file:
testsite_array.append(line)

This is possible because Python allows you to iterate over the file directly.

Alternatively, the more straightforward method, using f.readlines():

with open('topsites.txt') as my_file:
testsite_array = my_file.readlines()

How to read lines from file into array?

Do as below :

File.readlines('test.txt')

Read documentation :

arup@linux-wzza:~> ri IO::readlines

= IO::readlines

(from ruby site)
------------------------------------------------------------------------------
IO.readlines(name, sep=$/ [, open_args]) -> array
IO.readlines(name, limit [, open_args]) -> array
IO.readlines(name, sep, limit [, open_args]) -> array

------------------------------------------------------------------------------

Reads the entire file specified by name as individual lines, and
returns those lines in an array. Lines are separated by sep.

a = IO.readlines("testfile")
a[0] #=> "This is line one\n"

If the last argument is a hash, it's the keyword argument to open. See IO.read
for detail.

Example

arup@linux-wzza:~/Ruby> cat out.txt
name,age,location
Ram,12, UK
Jadu,11, USA
arup@linux-wzza:~/Ruby> ruby -e "p File::readlines('./out.txt')"
["name,age,location\n", "Ram,12, UK\n", "Jadu,11, USA\n"]
arup@linux-wzza:~/Ruby>

node.js: read a text file into an array. (Each line an item in the array.)

If you can fit the final data into an array then wouldn't you also be able to fit it in a string and split it, as has been suggested?
In any case if you would like to process the file one line at a time you can also try something like this:

var fs = require('fs');

function readLines(input, func) {
var remaining = '';

input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index > -1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});

input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}

function func(data) {
console.log('Line: ' + data);
}

var input = fs.createReadStream('lines.txt');
readLines(input, func);

EDIT: (in response to comment by phopkins) I think (at least in newer versions) substring does not copy data but creates a special SlicedString object (from a quick glance at the v8 source code). In any case here is a modification that avoids the mentioned substring (tested on a file several megabytes worth of "All work and no play makes Jack a dull boy"):

function readLines(input, func) {
var remaining = '';

input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
var last = 0;
while (index > -1) {
var line = remaining.substring(last, index);
last = index + 1;
func(line);
index = remaining.indexOf('\n', last);
}

remaining = remaining.substring(last);
});

input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}

Read lines of a text file into an array

That's a pretty non-android way of thinking of things.

Consider using res/values/strings.xml to store your quotes, then read a random one from there by using getResources().getStringArray(R.string.quotes), then generating a random integer between 0 and the size of that array.

Bonus of using resources - you can use the same identifiers, but change the quotes themselves based on region.

reading lines from text file into array

Multiple problems:

  • the PI macro is not properly parenthesized. It should be #define PI (4*atan2(1,1))
  • while (!feof(fp)) is always wrong. Use while (fgets(buf, 200, fp)) instead.
  • You cannot increment an array, you want to concatenate the string at the end of the array with strcat(buffarray, token); but you must initialize buffarray[0] to '\0' before the loop.

Here is a corrected version:

#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PI (4*atan2(1,1))

int main(int argc, char *argv[]) {
FILE *fp;
char buf[200];
char *token;
char buffarray[223920];
char filename[150];

if (argc < 2 || sscanf(argv[1], "%149s", filename) != 1) {
printf("missing command line argument\n");
return 1;
}

if ((fp = fopen(filename, "rt")) == NULL) {
printf("Failed in fopen %s: %s\n", filename, strerror(errno));
return 1;
}

*buffarray = '\0';
while (fgets(buf, sizeof buf, fp)) {
token = buf;
printf("buf is %s\n", buf);
strcat(buffarray, token);
}
fclose(fp);

printf("file contents:\n);
fputs(buffarray, stdout);
return 0;
}


Related Topics



Leave a reply



Submit