Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to print specific line in a file?

Status
Not open for further replies.

761210

IS-IT--Management
Jun 25, 2003
13
US
How to print specific line in a file?
 
What do you mean, specific? Or how do you specify it?
 
Need more info on 'specific', but here are some examples:

The source file is a '.profile' in my home directory that reads as follows:

alias vi='vim'


if [ $MACHINE = "Linux" ]
then
. $HOME/.bash_profile
. $HOME/.bashrc
fi

if [ ! "$LOGIN" ]
then
export LOGIN=$LOGNAME
fi


If I wanted just to show the line(s) that start with 'alias' I could do:

grep '^alias' .profile
alias vi='vim'

If I want to print out the 4th line, I could do:

sed '1,3d
5,$d' .profile

if [ $MACHINE = "Linux" ]


Just two quick examples. There are tons of other ways to do the above two examples (of course! TIMTOWTDI)

---
Batavus
 
Ok .. all I need is to have a specific line in a file to be printed on console. Example if i have a file:
hello
there
everyone

Say I only want to print line 2: there .. how can I do it?
 
[tt]gawk 'NR == 5 { print $0 }'[/tt]
would print out line 5.

//Daniel
 
Daniel,
I don't understand.
I need to read line 5 of a file. But your advice given doesn't provide any file input. Kindly advice.
 
You either pipe [tt]cat <filename>[/tt], but that would give me a UUOC award, or put the filename after the above command (which I accidentally left out), making the whole command [tt]gawk 'NR == 5 { print $0 }' <filename>[/tt].

//Daniel
 
Hi Daniel,
Further question: How do I assign the value of gawk 'NR == 5 { print $0 }' <filename> to a variable, say tmpLine?
Kindly advice.
 
As with the other commands above, putting it in backticks should work:
[tt]tmpLine=`gawk 'NR == 5 { print $0 }' <filename>`[/tt]

//Daniel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top