Find the answer to your Linux question:
Results 1 to 7 of 7
Hi all, is it possible to print only particular lines in a text file using SED? Say line 1, line3 and line 7 in /etc/passwd ? sed -n '1,7p' seems ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Feb 2004
    Posts
    1

    Print lines using SED


    Hi all, is it possible to print only particular lines in a text file using SED? Say line 1, line3 and line 7 in /etc/passwd ? sed -n '1,7p' seems to print line 1 till line 7 in a row. Many thanks

  2. #2
    Linux Newbie
    Join Date
    Dec 2005
    Posts
    104
    Im not sure if that is possable, but when a new user is added, those lines may change..Correct me if im wrong.

    You could get a line with a username by using Grep...
    If thats what you want.
    This:
    Code:
    cat /etc/passwd |grep nathanm
    Will return:
    Code:
    [root@emerald nathanm]# cat /etc/passwd |grep nathanm
    nathanm:x:501:501:Nathan Metcalf:/home/nathanm:/bin/bash
    [root@emerald nathanm]#
    And use AWK to seperate the line returned by grep by ":"

  3. #3
    Linux Newbie birdman's Avatar
    Join Date
    Mar 2006
    Location
    Ireland
    Posts
    141
    You could write a for loop to create something like this:

    echo `sed -n '1p' /etc/passwd`"\n"`sed -n '3p' /etc/passwd`

    Or you could use cat or grep to print out the line numbers and search for those.

    Not sure how else you could do it,

    All the best

  4. #4
    Linux Newbie
    Join Date
    Oct 2004
    Posts
    158
    You can create "patterned" selected lines like print every three lines:
    Code:
    gsed -n '3~3p'               # GNU sed 
    sed -n '3,${p;n;n;}'

  5. #5
    Linux User DThor's Avatar
    Join Date
    Jan 2006
    Location
    Ca..na...daaa....
    Posts
    319
    Sounds like one of those questions better posed by explaining why you want to extract specific line numbers. As mentioned, they change, usually it's not the line number that's relevant, but the content, for which grep is better.

    DT

  6. #6
    Just Joined!
    Join Date
    Apr 2006
    Posts
    11
    You can use sed to do this, though sed can be rather picky, for me sometimes anyway.

    I'd recommend just using the simplist "head -10 | tail -1" type of thing.

  7. #7
    Just Joined!
    Join Date
    Dec 2011
    Posts
    1
    if you want to print a list of lines lets say lines 1,2 and 10 you can use

    sed -n -e '1p' -e '2p' -e '10p' myfile.txt

    if the list of lines you want to print out is too long it's convenient to put them in a separate file lets call it list
    the content of list file should be like this

    1p
    2p
    10p

    and you can load the file with -f option
    sed -n -f list myfile.txt

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •