4

Input

[*] 111, 22, 33, 44

Output

111,22,33,44

Using sed command sed 's/^\[\*\][[:space:]]*//' file were able to display the output as 111, 22, 33, 44 which means space still there.

So what is the correct sed command?

  • 1
    If you just want to remove certain characters I find the GNU version of tr easier to use, which supports a -d parameter to delete characters instead of translating them and also supports certain character classes. In this case just tr -d '[*][:space:]' might work well for you. But if you really meant to only change lines with a [*] prefix you would be better of with sed. – David Ongaro Nov 21 '17 at 15:01
6

The short answer is that this should do what you want:

sed 's/[][*]\|[[:space:]]//g'

Test it out like so:

echo '[*] 111, 22, 33, 44' | sed 's/[][*]\|[[:space:]]//g'

Output:

111,22,33,44

A longer explanation follows.


The key ingredient that your expression was missing was the use of the g command to perform global substitution. Without this command only the first match on each line will be replaced.

The most counter-intuitive bit (in my opinion) of my solution is how to include the square brackets inside a character class. For that, we refer to the sed manual:

‘]’
    ends the bracket expression if it’s not the first list item.
    So, if you want to make the ‘]’ character a list item, you must put it first.

For further discussion on that topic, see the following post on SeverFault:

Alternatively, you could have taken your expression and piped it into another sed command, e.g.:

echo '[*] 111, 22, 33, 44' \
| sed 's/^\[\*\]//' \
| sed 's/[[:space:]]//g'
  • @αԋɱҽԃαмєяιcαη If this answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Nov 21 '17 at 13:20
  • @terdon i were unable to accept the answer within the first 7 minutes :d that's why i were waiting the time to done and was doing some other things :D anyway i will never forget to accept the answer for the man who spend time to help me :D so don't worry. – αԋɱҽԃ αмєяιcαη Nov 21 '17 at 13:44
  • @αԋɱҽԃαмєяιcαη oh hey, we all forget it from time to time! But thanks for remembering! – terdon Nov 21 '17 at 14:18

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.