Extract a part of one line from a file with sed

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
localhost

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
localhost

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

Replace the p command by a substitution that removes the unwanted part of the line.

sed -n '3 s/^[^=]*= *//p' installation.sh

You may want to match the line by keyword rather than by position.

sed -n 's/^ *POP3_SERVER_NAME *= *//p' installation.sh

Looks like you've got a config file. What you could do is similar to what Adam Siemeon/slm suggest:

sed -nr 's/[^=]+=\s*(.+)$/\1/p' filename

where [^=] excludes all '=' characters, + says one or more of the same type of character, this followed by an actual =, \s any whitespace (including tabs \t and new lines \n, \r\n, and plain spaces ' ', whereas * means zero or more of the same type, parentheses catch what's inside to place the matched character sequences into the \1, \2, ..., \n replacement placeholders, $ means the end of a line. This follows the typical replacement pattern of: s/.../.../modifiers. The command line option -r stands for extended regex syntax (as a matter of convenience) and -n means output nothing until or unless explcitly requested. The p modifier prints out the result.

You could make a global search with the g modifier like:

sed -nr 's/[^=]+=\s*(.+)$/\1 /pg' filename  # note the space after \1

so that you get a string separated by ' ' (could be \n, \t, or what have you) which you can process easily.

Both is valid provided your values preceded by the equation character span up to the end of a line and are not followed by comments or other characters with semantics deviating from a simple "value".


Edit:

I can't comment here yet on other's posts. To indicate the line just pass the line number, in your case 3, before s or before the initiating quote char (just like in vim).

sed -nr '3s/[^=]+=\s*(.+)$/\1/p' filename

Please take a look at info sed. For example, 3.2 and 4.7 are of particular interest to you.

Tags:

Sed