Computing.Net > Forums > Unix > Reading a specific line from file

Reading a specific line from file

Reply to Message Icon

Original Message
Name: Pras
Date: October 2, 2002 at 08:16:00 Pacific
Subject: Reading a specific line from file
OS: UNIX
CPU/Ram: N/A
Comment:

I have a file with 10000 lines.
I want to read the 8800th line into a variable without going through the complete file as it takes a long time. Also I don't know what text is in 8800th line.


Report Offensive Message For Removal


Response Number 1
Name: James Boothe
Date: October 2, 2002 at 08:48:29 Pacific
Reply: (edit)

unix will not be able to do a direct read on line 8800. But to pull that line:

line8800=`tail +8800 bigfile | head -1`


Report Offensive Follow Up For Removal

Response Number 2
Name: Parimal
Date: October 2, 2002 at 09:39:31 Pacific
Reply: (edit)

Hi Pras,
This is my script and it works great..I have tested it..

echo "Enter line number to print:\c"
read linenumber
echo "Enter Filename:\c"
read filename
echo "File is $filename and line is $linenumber"
count=`cat $filename|wc -l`
if test $linenumber -gt $count
then
echo "You entered line number $linenumber, while file has total $count lines"
exit
else
echo "Line is :"
head -$linenumber $filename|tee temp.txt|tail -1 temp.txt
rm -rf temp.txt
fi


-Parimal


Report Offensive Follow Up For Removal

Response Number 3
Name: jimbo
Date: October 2, 2002 at 09:51:16 Pacific
Reply: (edit)

> I want to read the 8800th line into a variable

VARIABLE=`sed -n '8800p' FILE`

-jim


Report Offensive Follow Up For Removal

Response Number 4
Name: Parimal
Date: October 2, 2002 at 09:53:35 Pacific
Reply: (edit)

To add to above, if you want to have output assigned to a variable then you can modify the line
head -$linenumber $filename|tee temp.txt|tail -1 temp.txt

& replace with this

line=`head -$linenumber $filename|tee temp.txt|tail -1 temp.txt`
echo $line


so the whole script would look like---->
echo "Enter line number to print:\c"
read linenumber
echo "Enter Filename:\c"
read filename
echo "File is $filename and line is $linenumber"
count=`cat $filename|wc -l`
if test $linenumber -gt $count
then
echo "You entered line number $linenumber, while file has total $count lines"
exit
else
echo "Line is :"
line=`head -$linenumber $filename|tee temp.txt|tail -1 temp.txt`
echo $line
rm -rf temp.txt
fi


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Reading a specific line from file

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 4 Days.
Discuss in The Lounge