Thursday, February 12, 2009

Break line in fixed width - linux fold command


Today I came to know about Linux 'fold' command, using which we can wrap each input line to fit in specified width.

If width is not specified using -w option, by default, 'fold' breaks lines wider than 80 columns. The output is split into as many lines as necessary.

Lets have one example to see how fold can be useful in breaking long lines in a file.

Print the alphabets from A-Z

$ echo "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

** The above can be output using Linux jot command i.e.
$ jot -c 26 A | tr '\n' ' '

If we need to break the above one line into 8 alphabets per line, we need to specify the width as 16.

$ echo "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" | fold -w 16

Output:
A B C D E F G H
I J K L M N O P
Q R S T U V W X
Y Z

Sed and Awk alternatives for the above task will be:

$ echo "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" | sed -e "s/.\{16\}/&\n/g"

$ echo "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" | awk 'BEGIN{n=1}{while(substr($0,n,16)){print substr($0,n,16);n+=16}}'

Also from man pages of 'fold' command, other useful options with 'fold' are:

`-b'
`--bytes'
Count bytes rather than columns, so that tabs, backspaces, and
carriage returns are each counted as taking up one column, just
like other characters.

`-s'
`--spaces'
Break at word boundaries: the line is broken after the last blank
before the maximum line length. If the line contains no such
blanks, the line is broken at the maximum line length as usual.

2 comments:

Ian Kelling said...

Good stuff. I have a long sed expression written down for wrapping on whitespace that I can forget about now.

Jadu Saikia said...

@Ian, thanks.

© Jadu Saikia www.UNIXCL.com