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
One fairly straightforward approach would be to replace the first "hash" by "hash space" only in lines that begin with "hash not space":
In regex variants that provide it, like Perl, you could use negative lookahead:
You can use
sed
"back-reference" like this:This is the code that solves my problem, thanks to @steeldriver and @FedonKadifeli:
Returns:
This code:
Or this more logic code:
Returns: