fold Command Examples in Linux

This tutorial explains Linux “fold” command, options and its usage with examples.

fold – Filter for folding lines.

DESCRIPTION

Wrap input lines in each FILE (standard input by default), writing to standard output. This breaks the lines to have a maximum of x width column position (or bytes).

SYNOPSIS

fold [ -bs ] [-w width | -width] [file]

OPTIONS

advertisement

-b
Count width in bytes rather than column positions.
-s
If a segment of a line contains a blank character within the first width column positions (or bytes), break the line after the last such blank character meeting the width constraints. If there is no blank character meeting the requirements, the -s option will have no effect for that output segment of the input line.
-w width | -width
Specify the maximum line length, in column positions (or bytes if -b is specified). If width is not a positive decimal number, an error is returned. The default value is 80.
file
A path name of a text file to be folded. If no file operands are specified, the standard input will be used.

EXAMPLES

1. Given the contents of file abc, fold works as follows if width is 20:

Free 30-Day C Certification Bootcamp is Live. Join Now!
$ cat abc
  This is a brief message to the Control Unit group.
     The new hp is now on-line. To send prints to it, type lj filename.
     If you have questions contact Sys. Adm. (x480).
     The printer is located in the stock room.
$ fold -w 20 abc
  This is a brief me
ssage to the Control
 Unit group.
     The new hp is n
ow on-line. To send 
prints to it, type l
j filename.
     If you have que
stions contact Sys. 
Adm. (x480).
     The printer is 
located in the stock
 room.

2. For processing large no. of files to set them to width of 65(say), we use shell program

for i in *.txt
do
  fold -sw 65 $i > $i.output
done

Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.

If you wish to look at all Linux commands and their usage examples, go to Linux Commands Tutorial.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.