Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

After running the following command, I get:

[root@yukiko /]# find / -iname .bashrc
/home/clamav/.bashrc
/home/vpopmail/.bashrc
/etc/skel/.bashrc
/root/.bashrc

But I would like to have a command that prints a specific line by supplying the command with the line number, for example:

[root@yukiko /]# find / -iname .bashrc | getline(2)
/home/vpopmail/.bashrc

Is there such a command on CentOS?

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

You could use a combination of head and tail:

find / -iname .bashrc | head -n 2 | tail -n 1

this will return the last one row of the first two rows (so the second row). You might be able to get head to do the job on its own if it has an option for skipping X number of rows (check man head). It is also not unlikely that there is another tool to do the job in the set that is the coretulis package included by most Linux variants so it migth be worth scanning the manual for this group of tools (see http://www.gnu.org/software/coreutils/manual/html_node/index.html or your local copy) a quick scan. It is worth a look anyway if only to refresh yourself on what tools are commonly available.

share|improve this answer
add comment
find / -name .bashrc | sed -n '2{p;q}'
share|improve this answer
2  
+1 for our good friend sed. With this the OP has the foundation for just what he wants, e.g.: getline () { LN=$1; shift; sed -n "${LN}{p;q}" "$@"; } –  pilcrow Feb 8 '10 at 22:04
    
And a +1 for your comment; that's a nice way of hiding sed syntax from those unfamiliar with it. –  njd Feb 10 '10 at 17:47
add comment

Here is a whip-up of a Perl script to do that

#!/usr/bin/perl
use strict; 
use warnings;

my $ln = $ARGV[0];
#note that further evolution may have a regular file here...
my $line = 1; 
my $wantedline;
while(<STDIN>)
{
  $wantedline = $_;
  last if($line++ == $ln);
}
print $wantedline;
share|improve this answer
    
Now that's a lot longer than a typical Perl one-liner... perl -ne 'if($.==2){print;last}' –  grawity Feb 10 '10 at 19:38
    
@grawity: That's OK, right? –  Paul Nathan Feb 11 '10 at 2:32
    
It's OK because it is more readable and uses a command line argument instead of hardcoding the number, but it's also not OK because 1) $wantedline is completely unneeded and 2) Perl already has a special var $. for current line number. –  grawity Feb 11 '10 at 13:51
    
@grawity: Readability trumps those concerns unless you're skilled in Perl. At least IMO. –  Paul Nathan Feb 11 '10 at 22:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.