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 Answers 3

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.

2
  • This is not removing first and last character, this is removing parentheses all over the place.
    – Tzen
    Nov 12, 2019 at 14:43
  • 1
    @Tzen good point, thanks, I rewrote the answer.
    – janos
    Nov 12, 2019 at 19:05
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
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.

1
  • Hmm. As Sethos noted, OP's own way should also work. It works in my terminal at least. Fedora 25 GNOME.
    – narwahl
    Mar 5, 2017 at 0:49

You must log in to answer this question.