41

How can I get second line in a file using SED

@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>

With the data that looks like above I want only to get

 GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC

5 Answers 5

54

You don't really need Sed, but if the pourpose is to learn... you can use -n

n read the next input line and starts processing the newline with the command rather than the first command

sed -n 2p somefile.txt

Edit: You can also improve the performance using the tip that manatwork mentions in his comment:

sed -n '2{p;q}' somefile.txt
3
  • 6
    In case you are sure there will be no more line 2 after line 2, you can spare some pointless processing by quiting after printing: sed -n '2{p;q}' somefile.txt.
    – manatwork
    Commented Aug 18, 2011 at 7:43
  • Good point @Manatwork, and a very interesting tutorial sehe. +1 for both.
    – Jonathan
    Commented Aug 18, 2011 at 8:16
  • 2
    Does not work on OS X. Is {p;q} is a GNU extension? IMO the correct answer should be sed '2q;d'.
    – j--
    Commented Dec 23, 2015 at 12:45
23

You always want the second line of a file? No need for SED:

head -2 file | tail -1
4
  • 3
    This needs 2 processes instead of one with sed. So on a performance point of view, sed is better.
    – jfg956
    Commented Aug 18, 2011 at 8:15
  • Very curious solution. Thumb up!
    – HongboZhu
    Commented Dec 3, 2014 at 15:14
  • wont work for multiple files, nice simplistic for one. Commented Mar 30, 2015 at 14:05
  • I tested this and they behave differently as well - a 2 line file with head and tail would return the first line still, while SED returns nothing
    – Rob
    Commented Jun 6, 2018 at 6:55
16

This will print the second line of every file:

awk 'FNR==2'

and this one only the second line of the first file:

awk 'NR==2'
7

This might work for you:

sed '2q;d' file
3
cat your_file | head -2 | tail -1
1
  • 2
    This is the superfluous cat I find myself using at times. Use this instead.
    – skytaker
    Commented Dec 9, 2019 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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