brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: fold -s -w 60 wraps long lines at spaces

Linux
~/tips/tip-shell-fold-wrap-long-lines

echo "a very long sentence that keeps going and going" | fold -s -w 20

Wraps long lines to a chosen width and breaks them at spaces instead of in the middle of words.

Long single-line text is annoying in a terminal, in an email draft or in a commit message. I used to reach for an editor, but fold does the job in a pipe.

fold -s -w 60 notes.txt
echo "a very long sentence that keeps going and going" | fold -s -w 20

-w sets the width in columns. Without it, the default is 80. -s tells fold to break at spaces, so a line is wrapped after the last blank that still fits in the width. That is the difference between readable output and words cut in half.

It reads from a file or from standard input, so it fits at the end of any pipeline. Paste a long paragraph into fold -s -w 72 and you get something you can put in a plain-text email or a commit body.

A small example of what comes out for the second command above:

a very long sentence
that keeps going and
going

Each output line is at most 20 columns, and fold wraps after a blank where it can.

The caveat is that fold is blunt. If a line has no blanks at all, such as a long URL, it is still cut at the width limit. It also knows nothing about paragraphs or indentation, it just counts columns. For text where that matters, fmt is the smarter tool, because it reflows whole paragraphs. For logs or one long line of text, fold is enough.

Further reading: fold(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link