3

I have to add a space after the # to every occurrence, only if the # is at the beginning of the line and after the # there is at least one character that is not the space. For example this code:

echo "# ok" | sed "s|^#[^ ]|# |g"

Returns # ok as expected, but this code:

echo "#ok" | sed "s|^#[^ ]|# |g"

Returns # k and not # ok as expected.
How do I get the # ok output?

Edit:

This is the code that solves my problem, thanks to @FedonKadifeli:

echo -e "#ok\n# ok\n #ok\n#ok #ok\n##ok #ok"

Returns:

#ok
# ok
 #ok
#ok #ok
##ok #ok

This code:

echo -e "#ok\n# ok\n #ok\n#ok #ok\n##ok #ok" | sed -r 's|^#(#*)([^[:space:]#])|#\1 \2|g'

Returns:

# ok
# ok
 #ok
# ok #ok
## ok #ok
5

You can use sed "back-reference" like this:

sed -r 's/^#([^ ])/# \1/'
| improve this answer | |
  • I have solved it! thank you! – Mario Palumbo Sep 25 at 14:40
6

One fairly straightforward approach would be to replace the first "hash" by "hash space" only in lines that begin with "hash not space":

$ echo "#ok" | sed "/^#[^ ]/s|#|# |"
# ok

In regex variants that provide it, like Perl, you could use negative lookahead:

$ echo "#ok" | perl -pe 's/^#(?! )/# /'
# ok
| improve this answer | |
-1

This is the code that solves my problem, thanks to @steeldriver and @FedonKadifeli:

echo -e "#ok\n#ok\n# ok\n# ok\n#ok\nnobegin #ok"

Returns:

#ok
#ok
# ok
# ok
#ok
nobegin #ok

This code:

echo -e "#ok\n#ok\n# ok\n# ok\n#ok\nnobegin #ok" | sed "\|^#[^[:space:]]|s|#|# |g"

Or this more logic code:

echo -e "#ok\n#ok\n# ok\n# ok\n#ok\nnobegin #ok" | sed -r "s|^#([^[:space:]])|# \1|g"

Returns:

# ok
# ok
# ok
# ok
# ok
nobegin #ok
| improve this answer | |
  • Edit your Q instead. – bac0n Sep 25 at 13:02

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.