16

I have a script that outputs a list of packages on a single long line separated by spaces. The information included in this line shall be inserted into a text file which is later presented to a user.

I want to split the long line into multiple lines with a defined maximum length, e.g. 80 characters, but the split should occur only at spaces (so some lines may be shorter if there is no space after exactly 80 characters and the next element would make it longer).

The case where a single entry is longer than 80 characters will probably never happen and I don't care if this entry is split up in the middle or results in a single longer line.

Basically, it's the same what most text editors do when auto wrapping is selected but I want to do it from a shell script.

Example Input:

libkrb5-3 libk5crypto3 openssh-server libc-bin base-files sysvinit-utils bind9-host python-minimal python-reportbug dnsutils perl libgnutls-openssl27 mutt reportbug libdns88 perl-base whois bash libgnutls26 perl-modules libapt-inst1.5 python2.7 libexpat1 libisccc80 libgssrpc4 apt-utils procmail apt locales liblwres80 libkrb5support0 python openssh-client multiarch-support libgcrypt11 dpkg libxml2 libbind9-80 wget libapt-pkg4.12 file ssh libkadm5clnt-mit8 libisccfg82 libkadm5srv-mit8 tzdata gpgv krb5-locales python2.7-minimal libgpgme11 openssl rsyslog libkdb5-6 host sysv-rc libgssapi-krb5-2 libisc84 libc6 initscripts sysvinit libmagic1 libssl1.0.0 gnupg

Desired example output:

libkrb5-3 libk5crypto3 openssh-server libc-bin base-files sysvinit-utils
bind9-host python-minimal python-reportbug dnsutils perl libgnutls-openssl27
mutt reportbug libdns88 perl-base whois bash libgnutls26 perl-modules
libapt-inst1.5 python2.7 libexpat1 libisccc80 libgssrpc4 apt-utils procmail apt
locales liblwres80 libkrb5support0 python openssh-client multiarch-support
libgcrypt11 dpkg libxml2 libbind9-80 wget libapt-pkg4.12 file ssh
libkadm5clnt-mit8 libisccfg82 libkadm5srv-mit8 tzdata gpgv krb5-locales
python2.7-minimal libgpgme11 openssl rsyslog libkdb5-6 host sysv-rc
libgssapi-krb5-2 libisc84 libc6 initscripts sysvinit libmagic1 libssl1.0.0 gnupg
28

What you want does fold:

fold -s -w80 file
  • -s: tells fold to break only at spaces
  • -w80: declared the width
  • fold: also reads from stdin: echo "..." | fold -s -w80
  • 1
    Perfect, thanks a lot. I was sure that there must be a simple command but I never heard of fold. – jan Oct 15 '14 at 14:33

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.