Read a File and Split Each Line into Multiple Variables

read a file and split each line into multiple variables

read can do this itself. See BashFAQ #1.

while IFS=$'\t' read -r key value; do
echo "First Var is $key - Remaining Line Contents Are $value"
done

Note that if you want to discard any content after the second column (rather than appending that content to the value), this would instead be:

while IFS=$'\t' read -r key value _; do
echo "First Var is $key - Second Var is $value"
done

If you want to store the IDs in such a way as to be able to look them up by name, an associative array (added in bash 4.0) is the right tool:

declare -A color_ids=( )
while IFS=$'\t' read -r key value; do
color_ids[$key]=$value
done

for name in "${!color_ids[@]}"; do
value=${color_ids[$name]}
echo "Stored name $name with value $value"
done

How to split up a line in a text file into multiple variables in C

You can sscanf() to split the line.

Since I was bored, I did this:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char* model;
float version;
int price;
char* color;
}
vehicle;

bool vehicle_create( vehicle* v, const char* model, float version, int price, const char* color )
{
v->model = strdup( model );
if (!(v->model)) return false;

v->version = version;
v->price = price;
v->color = strdup( color );

if (v->color) return true;

free( v->model );
return false;
}

void vehicle_destroy( vehicle* v )
{
if (!v) return;
if (v->model) free( v->model ); v->model = NULL;
if (v->color) free( v->color ); v->color = NULL;
}

bool read_vehicle( FILE* f, vehicle* v )
{
char model[ 50 ];
char color[ 50 ];
char line[ 200 ];
float version;
int price;

if (!fgets( line, sizeof(line), f ))
return false;

if (4 != sscanf( line, "%50s %f %d %50s", model, &version, &price, color ))
return false;

return vehicle_create( v, model, version, price, color );
}

size_t read_vehicle_inventory( FILE* f, vehicle* vs, size_t n )
{
size_t count = 0;
while (count < n
&& read_vehicle( f, vs + count ))
count += 1;
return count;
}

int main()
{
const size_t MAX_INVENTORY_SIZE = 100;
vehicle inventory[ MAX_INVENTORY_SIZE ];
size_t inventory_size = 0;

// Load inventory from file
inventory_size = read_vehicle_inventory( stdin, inventory, MAX_INVENTORY_SIZE );

printf( "inventory size = %d\n", (int)inventory_size );

// Display the inventory
for (size_t n = 0; n < inventory_size; n++)
printf( "%s %s %f is $%d\n",
inventory[ n ].color,
inventory[ n ].model,
inventory[ n ].version,
inventory[ n ].price );

// Free inventory
for (size_t n = 0; n < inventory_size; n++)
vehicle_destroy( inventory + n );

return 0;
}

Enjoy.

Read file and split each line into multiple variable in C++

What is the best way to split each line?

I would simply call while(std::getline(stream, line) to read each line, then for each read line, I would put it into a istringstream (iss), and call while(std::getline(iss, value, '#')) repeatedly (with stream being your initial stream, and line and value being strings). The first value read in the inner loop will be the key; the rest, will be the values.

Some code:

auto read_file(std::istream& in)
{
using namespace std;
map<string, vector<string>> values;
string line;
while(getline(in, line))
{
istringstream linein{ line };
string key, value;
if(!getline(linein, key, '#'))
throw runtime_error{ "bad file format" };
while(getline(linein, value, '#') && !value.empty())
values[key].emplace_back(move(value));
}
return values;
}

std::ifstream in{ "file-of-this-type.txt" };
auto values = read_file(in);

How to split a line of a txt file into different variables?

You should use split() :

String names[] = new String[10];
int numbr[] = new int[10];
for(int i = 0; i<names.length; i++){
String line = reader.readLine();
if(line != null){
names[i] = line.split(" ")[0];
numbr[i] = Integer.parseInt(line.split(" ")[1]);

}

}

Ref : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Python3, read line by line from txt file and split line into two variables

Use readlines to read the text then iterate through the text

with open(filepath, 'r') as fp:
lines = fp.readlines()
for x in lines:
sp = x.split(":")
firstname, lastname = sp[0], sp[1]
print(firstname,lastname)

Read a file and split each line into two variables with bash program

Here is how you would debug your program:

#!/bin/bash

while read ligne
do
var1=$(echo $ligne | cut -f1 -d' ')
var2=$(echo $ligne | cut -f2 -d' ')

if [[ "$var1" != "" && "$var2" != "" ]]; then
echo "$var1" '|' "$var2"
#java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer "$var1" "$var2"
else
echo "Vars Not Found"
#java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer
fi
done < mm.txt

Running this gives the following output:

vehicle car | vehicle car
computer program | computer program
volley ball | volley ball

This means that your cut command is not correct. You have a few options to fix it:

  1. Use multi-variable read as user3035772 pointed out. This is less flexible because it relies on the separator being $IFS, which you are implicitly not agreeing to.
  2. Fix the delimiter in mm.txt to be - as the -d- flag of the cut command requires:

    vehicle-car
    computer-program
    volley-ball
  3. Fix the cut command to require a space delimiter as you have in mm.txt: cut -f1 -d' '.

How to read variables from file, with multiple variables per line?

I think all you're looking for is to read multiple variables per line: the read command can assign words to variables by itself.

while read -r first second third; do
do_stuff_with "$first"
do_stuff_with "$second"
do_stuff_with "$third"
done < ./test.txt


Related Topics



Leave a reply



Submit