1

The following sed syntax deletes the first @ character if it exists in a string:

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

But how to change it to delete the @ character only if it's in the third position? For example, I would need to delete it in the following line:

 AB@CDEF

I need the script to verify if the third character is @, and if so then to delete it from the line.

2

You can use

sed 's/^\(..\)@\(.*\)/\1\2/'
  • Very good many THX yael – yael Jun 28 '10 at 7:13
  • you do not need the rest of the line, s/^\(..\)@/\1' is just fine. – akira Jun 28 '10 at 7:22
1

To generalize for any character at any given position n:

sed 's/^\(.\{2\}\)./\1/'

which deletes the third character. Just change the number "2" to n-1.

You can use a variable like this:

n=2
echo "$line" | sed "s/^\(.\{${n}\}\)./\1/"
0
% sed -e '/^..@/ { s,^\(..\)@,\1, }'

means:

  • if line starts with 3 characters, the third is a '@'
  • throw out the @, but keep the first chars

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.