Open In App

fold command in Linux with examples

Improve
Improve
Like Article
Like
Save
Share
Report

The fold command in Linux wraps each line in an input file to fit a specified width and prints it to the standard output. By default, it wraps lines at a maximum width of 80 columns, which is configurable. To fold input using the fold command pass a file or standard input to the command. 

Syntax of `fold` command in Linux 

fold [OPTION] [FILE]

We can specify options that will control line folding behavior and provide a file as input for processing. Consider if no file is specified, `fold` read from standard input.

Practical implementation of the `fold` command in Linux

fold GfG.txt
fold GfG.txt

fold GfG.txt

In the above example, we have passed a text file named GfG to the fold command and as you can see in the output it wraps the line up to 80 columns.

Different options available in the `fold` command

Wrapping Lines with the `-w` option in `fold` command

By using this option in the fold command, we can limit the width by the number of columns. Using this command, we change the column width from the default width 80.

Syntax:

fold -w[n] GfG.txt
fold -w[n] GfG.txt

fold -w[n] GfG.txt

 In the above example, we wrap the lines of GfG.txt to a width of 60 columns.

Handling Nonprinting Characters with the `-b` option

This option of fold command is used to limit the width of the output by the number of bytes rather than the number of columns. By using this we can enforce the width of the output to the number of bytes. 

Syntax:

fold -b[n] GfG.txt
fold -b[n] GfG.txt

fold -b[n] GfG.txt

In the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes.

Truncating Lines with the `-s` option

This option is used to break the lines on spaces so that words are not broken. If a segment of the line contains a blank character within the first width column positions, break the line after the last such blank character meeting the width constraints. 

Syntax:

fold -w[n] -s GfG.txt
fold -w[n] -s GfG.txt

fold -w[n] -s GfG.txt

If you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines.

Conclusion

In this article we have discussed `fold` command in Linux which offers a convenient way to wrap or truncate line in the text files. We have discussed some common options such as `-w`, `-s` and `-b. Overall, we can say that this versatility empowers us to improve readability and fit content within specific constraints.


Last Updated : 05 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads