0

I need to append a URL (http://localhost:3128) contained in the $http_proxy env var at the end of all the lines starting with PATTERN of a single file.

$ sed "/^PATTERN/ s/.*/& test/" somefile

It works quite well, but as soon as I replace test with $http_proxy, sed will complain because of the // inside it:

$ sed "/^PATTERN/ s/.*/& $http_proxy/" somefile
sed: -e expression #1, char 25: unknown option to `s'

So I tried using # as a separator (as suggested here for instance), but then seddoesn't have any effect, like if the pattern suddenly didn't match anymore:

$ sed "#^PATTERN# s#.*#& $http_proxy#" somefile

Any idea?

Community
  • 1
  • 1
Anto
  • 6,806
  • 8
  • 43
  • 65
  • 1
    escape `\#` in range selector (first `#`) or use standard `/` for this range (and keep the `#` for `s` separator. you can also use `sed "s#^PATTERN.*#& $http_proxy#" somefile` – NeronLeVelu Feb 06 '15 at 15:12
  • Don't use the word "pattern" as it's highly ambiguous. Are you searching for a number, a string, or a regexp? Do you want a partial match or a full match? If a full match, what delimits the section of text you are trying to match on - a number of characters, or a specific character or something else? – Ed Morton Feb 06 '15 at 15:49
  • You've got correct answers already. One extra tip is that you can simplify your pattern. Try something like `sed "/pattern/s#$# $htttp_proxy#"` You could escape the first dollar sign if you want, but at least in bash and sh, you don't need to. If you're doing this in csh or tcsh, you might need to `sed "/pattern/s#"'$'"# $http_proxy#"` – ghoti Feb 06 '15 at 16:04

3 Answers3

1

Use a different sed delimiter in s/// part only. And ypy don't need to put & in the replacement part since you're trying to append the string at the last, replacing the end of the line $ would be enough.

sed "/^PATTERN/s~$~ $http_proxy~" somefile
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

Use a tool that is unaffected by delimiters or variable content:

$ cat file
foo bar
PATTERN here
some line

$ awk -v pxy="$http_proxy" '/^PATTERN/{$0=$0" "pxy} 1' file             
foo bar
PATTERN here http://localhost:3128
some line
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

Apparently in this case the first delimiter has to be preceded with \:

$ sed "\#^PATTERN# s#.*#& $http_proxy#" somefile

Solves it indeed.

Community
  • 1
  • 1
Anto
  • 6,806
  • 8
  • 43
  • 65