1

How do I remove the , character after a specific word?

For example, I want to delete the , character after the word IBM

  IBM, Inc.:APP-VM-Core:4.4.2.0:04,

the expected results should be

  IBM Inc.:APP-VM-Core:4.4.2.0:04,

Meanwhile I do the following

   echo “IBM, Inc.:APP-VM-Core:4.4.2.0:04,” | sed s'/,//'

but the problem is that it deletes every , character, no matter what the first word was before the ,. In my case I want to delete the , only after IBM.

Example:

echo "APPLE, Inc.:APP-VM-Core:4.4.2.0:04,"| sed s'/,//'

APPLE Inc.:APP-VM-Core:4.4.2.0:04,

but should be as

APPLE, Inc.:APP-VM-Core:4.4.2.0:04, 
1
  • 2
    You can do it using awk. For example: echo IBM, Inc.:APP-VM-Core:4.4.2.0:04, | awk '/IBM/{sub(/,/,"")}1' Mar 24, 2015 at 14:49

2 Answers 2

2

Try:

$ echo "IBM, Inc.:APP-VM-Core:4.4.2.0:04," | sed '/^ *IBM/s/,//'
IBM Inc.:APP-VM-Core:4.4.2.0:04,

or:

$ echo "IBM, Inc.:APP-VM-Core:4.4.2.0:04," | sed 's/^\( *IBM\),/\1/'
IBM Inc.:APP-VM-Core:4.4.2.0:04,
2
  • what in case we have spaces between begin of line to IBM Mar 24, 2015 at 15:21
  • @maihabunash: Updated my answer.
    – cuonglm
    Mar 24, 2015 at 15:33
1

If you are trying to modify a file you'd rather use ex or ed but definitely not sed. Why not sed?

sed is a Stream EDitor and you'd modify the data coming from a stream with it.

Using ex you could do the following

ex -sc '%s/IBM,/IBM/g|x' file wheren file is your filename.

As alternative. If you want to remove leading spaces or tabs you will need more than ^ *. For example. The solution would be using awk as follow:

awk '{sub(/^[ \t]+IBM,/,"IBM");};1' input_file > output_file

or

awk '{sub(/^[[:blank:]]*IBM,/,"IBM");};1' input_file > output_file

Mind you. ^ * will not be able to detect tabs.

You also can use ex as explained earlier but now including the regular expression to match only the line beginning with spaces and including the pattern IBM

ex -sc '%s/^[[:blank:]]*IBM,/IBM/g|x' input_file
1
  • To those who are downvoting the answer. Please write a comment at least to demonstrate the flaws in the answer. This way we all can provide better answers in the future. It could help me a lot to improve my writing and or explanation! Thanks! Mar 24, 2015 at 15:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .