user3429531
user3429531

Reputation: 355

reading text file - bash

I am trying to read a text file-"info.txt" which contains the following information

info.txt

1,john,23
2,mary,21

what I want to do is to store each columns into a variable and print any one of the columns out.

I know this may seems simple to you guys but I am new to writing bash script, I only know how to read the file but I don't know how to delimit the , away and need help. Thanks.

while read -r columnOne columnTwo columnThree
do 
echo  $columnOne
done < "info.txt"

output

1,
2,

expected output

1
2

Upvotes: 1

Views: 3225

Answers (2)

iarroyo
iarroyo

Reputation: 2444

Is good to check if the file exists too.

#!/bin/bash
INPUT=./info.txt
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read -r columnOne columnTwo columnThree
do 
    echo "columnOne : $columnOne"
    echo "columnTwo : $columnTwo"
    echo "columnThree : $columnThree"
done < $INPUT
IFS=$OLDIFS

Upvotes: 0

William Pursell
William Pursell

Reputation: 212654

You need to set the record separator:

while IFS=, read -r columnOne columnTwo columnThree
do 
echo "$columnOne"
done < info.txt

Upvotes: 4

Related Questions