LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to read data from a text file? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-read-data-from-a-text-file-4175521922/)

Vipul_sharma11 10-13-2014 02:44 AM

How to read data from a text file?
 
Hi All,

I have a text file with Name and Address in it.

<Name>|<Address>

Amit|32, Rajpura Road, Dehradun
Sumit|123, Shahbad, Ambala

and so on....

I want to fetch the address when I enter the name.

Can anyone help me please?

pan64 10-13-2014 02:46 AM

just try the grep command, see the man page or look for tutorials and/or examples

715509387 10-13-2014 02:56 AM

try it
Code:

[root@svn252 ~]# cat URFILE
Amit|32, Rajpura Road, Dehradun
Sumit|123, Shahbad, Ambala
[root@svn252 ~]# awk -F'|' '$1=="Sumit"{print $2}' URFILE
123, Shahbad, Ambala
[root@svn252 ~]# awk -F'|' '$1=="Amit"{print $2}' URFILE
32, Rajpura Road, Dehradun
[root@svn252 ~]#


Vipul_sharma11 10-13-2014 02:57 AM

Thanks
 
hi,

thanks for the suggestion.

i want to read input from user and then take address from file.

can you please tell me how to read the file line by line?

nisagnel 10-13-2014 03:15 AM

Hi Vipul,

You can do it using bash script like below.
Assume that you have file "details.txt" which has name and address.

#!/bin/bash

## read name from the user
read NAME

## now grep the name from the details.txt
cat details.txt | grep $NAME


..hope this will help you.

rupal.chawla 10-13-2014 03:58 AM

You can try using 'grep' command

Eg. your details are in file 'text.txt'

type in command:
cat text.txt| grep "name"

Output:
Name Address



Happy Learning :)

---------- Post added 10-13-14 at 02:58 AM ----------

You can try using 'grep' command

Eg. your details are in file 'text.txt'

type in command:
cat text.txt| grep "name"

Output:
Name Address



Happy Learning :)

SAbhi 10-13-2014 04:50 AM

Since you didnt mentioned what you tried, i will take it as after a small guidance you would try it yourself by looking into some examples:

So i would prefer something like :
Code:

#declare filename as variable $filename
#read a variable say $inputname
#use grep to fetch users all details, instead of using cat. Avoiding a useless use of commands
grep $inputname $filename
#you can use awk, cut and further more commandsdepending upon your requirement, see man pages and examples as 'pan64' told.
#if there is any iteration needed you can use while loop to do the due
while read $variable; do something_with_variable;done< $filename

let us know if you ty and fail with what you tried, we can help suggesting better option.


All times are GMT -5. The time now is 03:59 PM.