Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I've got a long line that I want to insert a space every 4 characters, on a single lone line of solid text to make it easier to read, what's the simplest way to do this? also I should be able to input the line from a pipe. e.g.

echo "foobarbazblargblurg" | <some command here>

gives

foob arba zbla rgbl urg
share|improve this question

2 Answers 2

up vote 20 down vote accepted

Use sed as follows:

$ echo "foobarbazblargblurg" | sed 's/.\{4\}/& /g'
foob arba zbla rgbl urg
share|improve this answer
    
cursing that was so close to the sed I tried first I could kick myself. –  xenoterracide Jan 17 '11 at 14:29
1  
Just curious, what's the '&' accomplish? Oh, it's a standin for 'the thing what just matched'. Silly me. –  Omnifarious Aug 27 '12 at 5:25

I'm going to answer by only inserting spaces as required so a space appears at least after every 4 characters on a line; not sure which way you want to handle this case. For example, given input of "aa bbccdd", you'd get output "aa bbcc dd" rather than "aa b bccd d".

I'm using Perl for lookahead, but I'm not very familiar with Perl in general, so there may be tweaks needed:

$ echo "foobarbazblargblurg" | perl -wp -e 's/[^ ]{4}(?=[^\n ])/$& /g'
foob arba zbla rgbl urg

$ echo 'aa bbccdd' | perl -wp -e 's/[^ ]{4}(?=[^\n ])/$& /g'
aa bbcc dd
# not 'aa b bccd d'!

$ echo 'some input' | perl -wp -e 's/[^ ]{4}(?=[^\n ])/$& /g'
some inpu t
# not 'some  inp ut'!

$ echo $'aabb\nc cddee' | perl -wp -e 's/[^ ]{4}(?=[^\n ])/$& /g' | 
> while read; do echo "${REPLY}x"; done
aabbx
c cdde ex
# no spaces added at the end of the first line (while loop to add to the end of
# the line and show this)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.