22

How does one delete the first known character in a string with sed?

For example, say I want to delete the first character (which is @) in the string "@ABCDEFG1234"

I want sed to verify whether "@" exists as the first character. If so, it should delete the character.

Pops
  • 8,473
yael
  • 539

3 Answers3

31

There's no need to capture and replace.

sed 's/^@//'

This replaces the character @ when it's first ^ in the string, with nothing. Thus, deleting it.

johnny
  • 912
17

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

^ means beginning of the string

@ your known char

(.*) the rest, captured

then captured block will be substituted to output Sorry, can't test it at the moment, but should be something like that

Pablo
  • 4,755
  • 19
  • 65
  • 101
  • I want to delete + which does not need to be escaped although it stands for 1 or more in regex. – Timo Nov 04 '20 at 07:56
2

You can do this instead.

sed 's/^.//'

^ - Starting character 
. - No of charactes(.. means two characters)

Example :

echo test123 | sed 's/^.//'
est123
echo test123 | sed 's/^..//'
st123
  • 2
    The question says “I want sed to verify whether "@" exists as the first character. If so, it should delete the character.” Your answer deletes the first character of each line no matter what is it. For example, if a line contains test123, it looks like the OP wants it left alone. – Scott - Слава Україні Mar 12 '18 at 03:57
  • I like the quick solution of Prakaash, but @Scott you are right when reading the OP carefully. In most of the cases, you do want a distinct character and not any. – Timo Nov 04 '20 at 07:54