0

This seems too easy but still can't get it work. I have:

-X-1.5

and need:

-X1.5

Using:

echo -X-1.5 | tr -d '-'

gives:

X1.5

which it's close, but not close enough.

Any pointers are welcome,

4

Another sed solution

echo "-X-1.5" | sed 's/-//2'

Substitute the second occurrence of - with nothing.

3

If you know that the character to delete is at position 2 (starting counting from 0), you can do this:

VAR="-X-1.5"
echo "${VAR:0:2}${VAR:3}"

which will give -X1.5.

If it were the first instance of a character that you wanted to delete, but you didn't know its position in advance, you could do this:

VAR="X-1.5-oh"
echo "${VAR/-/}"

which will give X1.5-oh.

1

Since the part to remove happens not to be at the beginning, end, nor is this a complete removal, it rules out a lot of generic shortcuts in favor of something more specific to match a known pattern, so it really depends on what the pattern will be..

If for example the pattern is always going to be a -X followed by - which you wish to remove, you can, for example:

$ echo "-X-1.5" | sed 's/-X-/-X/g'

Results:

-X1.5
  • searches for -X-
  • replaces with -X
  • /g to perform it greedily meaning all such occurrences, in case you have -X-1.5-X-2.5-X-3.5 etc

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.