Insert space between characters using sed

Input:

Youcaneasilydothisbyhighlightingyourcode.

Putting space after three characters.

You can eas ily dot his byh igh lig hti ngy our cod e. 

How can i do this using sed?

echo "Youcaneasilydothisbyhighlightingyourcode." | sed 's/\(.\{3\}\)/\1 /g'
1 Like

Or you can just use &:

sed 's/.\{3\}/& /g'
1 Like

Thank you all.

To prevent space from being added at the end:

#!/usr/bin/env gawk

{
	do {
		a = $0
		$0 = gensub(/([^[:blank:]]{3})([^[:blank:]])/, "\\1 \\2", "", a)
	} while (a != $0)

	print
}

... | gawk --re-interval -f script.awk

Or one-liner:

... | gawk --re-interval '{ do { a = $0; $0 = gensub(/([^[:blank:]]{3})([^[:blank:]])/, "\\1 \\2", "", a); } while (a != $0); } 1'

It's still consistent even if blank characters exist along or at the end of the string.

Or even:

sed 's/.../& /g'

Ow konsolebox already almost gave the same solution..

echo "Youcaneasilydothisbyhighlightingyourcode." |awk 'BEGIN{FS=OFS=""}{for (i=1;i<=NF;i++) {if (i%3==0) $i=$i " "}}1'
1 Like

Why is the last '1' used for?

}}1'

in awk 1 = print $0

More like awk decides to print depending on status of the last statement.

awk '/<false pattern>/'

Will not make a print. While

awk '/<true pattern>/'

will... Anything that's similar to (>0) means true.

Try these commands and see what it means

echo a | awk '0'
echo b | awk '1'
echo c | awk '2
echo d | awk '/d/'
echo e | awk '!/e/'
echo f | awk '/z/'

Or maybe it's just a condition placed at the last.

# echo "Youcaneasilydothisbyhighlightingyourcode." | echo `fold -w 3`
You can eas ily dot his byh igh lig hti ngy our cod e.