1

I need sed to remove first and last character of the line for instance source

(192.168.3.0)

result

192.168.3.0

trying this way:

sed 's/^.\(.*\).$/\1/'

but then it removes 0 character as well

how to-avoid this behavior ?

3 Answers3

5

As others have pointed out, the sed pattern you used is not correct, and it can be fixed to remove the first and last characters correctly.

Alternatively, in your particular example, if all you really want to do is remove the parentheses (leaving only the IP address), then a simpler approach can do the job.

For example, this tr filters out all parentheses from its input:

tr -d '()'

This is equivalent to the following sed:

sed -e 's/[()]//g'

If you really want to know how to remove the first and last characters, then see the other answers.

janos
  • 808
  • 1
  • 6
  • 22
2

How about this:

$ echo "(192.168.3.0)" | sed 's/^.//;s/.$//'
192.168.3.0

Although your command is also working:

$ echo "(192.168.3.0)" | sed 's/^.\(.*\).$/\1/'
192.168.3.0
Sethos II
  • 507
  • 4
  • 7
  • 18
0

Answers provided are correct. janos's answer is more ideal for your situation but not generalized. To provide a couple more ways following up on Sethos II's response:

$ echo "(192.168.3.0)" | sed -E 's/(^.)|(.$)//g'
192.168.3.0

$ echo "(192.168.3.0)" | sed 's/\(^.\)\|\(.$\)//g'
192.168.3.0

All four are valid. TMTOWTDI.

narwahl
  • 33
  • 7
  • Hmm. As Sethos noted, OP's own way should also work. It works in my terminal at least. Fedora 25 GNOME. – narwahl Mar 05 '17 at 00:49