Extract a part of one line from a file with sed

  • I want to read one part of one line from a file. For example:

    POP3_SERVER_NAME = localhost

    I want to return only localhost, using sed.

    This text is on the third line. I do this to extract the line:

    sed -n '3p' installation.sh

    How do I extract only the localhost part?

  • awk might be a better tool here.

    $ cat test.dat
    LINE 1
    LINE 2
    POP3_SERVER_NAME = localhost

    Search for lines that contain "POP3_SERVER_NAME"; print the last field. This doesn't depend on POP3_SERVER_NAME always being on line 3, which is probably a Good Thing.

    $ awk '/POP3_SERVER_NAME/{print $NF}' test.dat

    Depending on your application, you might need to make the regular expression more stringent. For example, you might want to match only that line that starts with POP3_SERVER_NAME.

    $ awk '/^POP3_SERVER_NAME/{print $NF}' test.dat

    Using sed is a little less intuitive. (Thanks, I'm aware of the irony.) Address the line that contains POP3_SERVER_NAME anywhere. Substitute an empty string for all the text from the beginning of the line to the optional space following "=". Then print.

    sed -n -e '/POP3_SERVER_NAME/ s/.*\= *//p' test.dat

    The `awk` command is nice - but only if you've got spaces around the `=`. It won't work for `POP3_SERVER_NAME=localhost`.

    @Marcel, You can change the delimiter used by `awk` from spaces to something else using `-F`. For instance: `-F "="` will use `=` as a delimiter in the case you mention.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM