Find the answer to your Linux question:
Results 1 to 7 of 7
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #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
    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.
    cat /etc/passwd |grep nathanm
    Will return:
    [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
    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. $spacer_open
  5. #4
    You can create "patterned" selected lines like print every three lines:
    gsed -n '3~3p'               # GNU sed 
    sed -n '3,${p;n;n;}'

  6. #5
    Linux User DThor's Avatar
    Join Date
    Jan 2006
    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.


  7. #6
    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.

  8. #7
    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


    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