LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   "How to read lines from a file" (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-read-lines-from-a-file-617856/)

sharath.bv 02-01-2008 01:39 AM

"How to read lines from a file"
 
Hi,

I want to read lines from a file line-by-line and to display those lines on the terminal.
Can any one please provide a shell script for this.:study:

lazlow 02-01-2008 01:49 AM

cat filename | more -1
The "|" is the pipe sysmbol (shift \ on my keyboard).

eoo 02-01-2008 01:55 AM

Hi,

I'm not sure what you're trying to do, but I'd use sed, e.g.

Quote:

sed -n "${i}p" $file
A longer longer example would be something like

Quote:

#! /bin/bash

file=/etc/fstab
nlines=$(wc -l $file | cut -f1 -d' ')
i=0

while [ $i -le $nlines ]
do
echo "Give me a line number"
read i
sed -n "${i}p" $file
done

echo "Reached end"
Hope this helps :)

Cheers

Disillusionist 02-01-2008 02:34 AM

Quote:

Originally Posted by sharath.bv (Post 3042049)
Hi,

I want to read lines from a file line-by-line and to display those lines on the terminal.
Can any one please provide a shell script for this.:study:

This is obviously just a starting point, so please forgive me for asking.

What are you trying to achieve?

To read each line into a variable you could do:
Code:

#!/bin/bash
cat myfile|while read line
do
  ##perform some checks
  echo $line
done

However, this strips out any leading spaces or tab characters, therefore you may not get what you are after.

To do the same thing in Perl (which doesn't strip out leading spaces or tab characters):
Code:

#!/usr/bin/perl
open(INPUT, "myfile") or die "Could not open input file";

while (<INPUT>) {
  ##perform some checks
  print;
}

close(INPUT);


sharath.bv 02-01-2008 03:41 AM

Thanks
 
Thanks all,
i got the answer.........:)

H_TeXMeX_H 02-01-2008 07:47 AM

The simplest and most readable way is (IMO):
Code:

while read line
do
  echo $line
done < file



All times are GMT -5. The time now is 10:00 PM.