Exclude character in a given position?

Asked

Viewed 2,318 times

4

How do I delete a certain character in a certain shell position?

I’ve tried with sed, but I can’t get into position either, just the pattern.

",45123","B23142DHAS675"

What I wanted was to erase the , which is in the second position of the string, but in case there is no , nothing should do.

2 answers

2


You can do it like this:

~$ echo ",45123","B23142DHAS675" | sed 's/.//7'
,45123B23142DHAS675

Where 7 is the position of the character to be removed. An alternative:

~$ echo ",45123","B23142DHAS675" | sed 's/\,//2'
,45123B23142DHAS675

The above command removes the second occurrence of ,.

  • Actually I would like the result to be: "45123","B23142DHAS675" - only to delete the "," which is in second position.

  • Perfect, @DBX8! Thanks!

1

Use a regular expression that holds the first n - 1 characters, check the character n is what you want, and save the remaining characters.

 echo "abcdef nao sera removido
a,cdef será removido
A,BCD será removido" | sed -r 's/^(.),(.*)$/\1\2/'

Upshot:

abcdef nao sera removido
acdef será removido
ABCD será removido
  • I would like you to just delete the "," from the second position, not the entire content. That the result would look like this: Actually I would like the result to be: "45123","B23142DHAS675"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.