tags:

views:

392

answers:

2

In *nix, how do I display (cat) a file with no line-wrapping: longer lines should be cut such that they fit into screen's width.

+4  A: 

You may be looking for fmt:

cat file | fmt

This pretty aggressively reformats your text, so it may do more than what you want.

Alternatively, the cut command can cut text to a specific column width, discarding text beyond the right margin:

cat file | cut -c1-80

Another handy option is the less -S command, which displays a file in a full screen window with left/right scrolling for long lines:

less -S file
Greg Hewgill
Indeed, it does more than I want: it concatenates lines.
Alexandru
Actually, I'm watching the content of the file using watch "cat file" so I can't use less.cat file | cut -c1-80 did the trick, partially. Any way to adjust the cut to the screen size?
Alexandru
You may have the environment variable `$COLUMNS` defined: try`cut -c1-$COLUMNS file`
mobrule
You can use watch like: `watch "cat file | cut -c1-$COLUMNS"` so the pipe is executed by watch (without the quotes then `cut` will be cutting the output of `watch` which is probably not going to work well).
Greg Hewgill
$COLUMNS doesn't work inside a shell script, any alternative?
Alexandru
`stty -a` on my system prints the number of columns on the first line. So try: `stty -a|head -1|awk '{print $6}'`
Greg Hewgill
+6  A: 

Note that cut accepts a filename as an argument.

This seems to work for me:

watch 'bash -c "cut -c -$COLUMNS file"'

For testing, I added a right margin:

watch 'bash -c "cut -c -$(($COLUMNS-10)) file"'

When I resized my terminal, the truncation was updated to match.

Dennis Williamson
Dennis, try the following script: http://dpaste.com/111286/
Alexandru
When I run your script `watch ./colscript`, I see 80 displayed. When I change the width by dragging the edge of the window (I'm using PuTTY) the number changes to match. What do you see?
Dennis Williamson
I see nothing, but I figured out why: different bash versions.watch ./colscript works on bash 4.0 (my computer), but not on bash 3.0 (a remote computer)../colscript doesn't work on any of the two versions.
Alexandru
`echo $BASH_VERSION` gives me "3.2.48(1)-release" The reason that running `./colscript` from the command line echoes a blank line is that `$COLUMNS` is only populated for interactive shells. You can try added `-i` at the end of the first line of `./colscript` so you have `#!/bin/bash -i`
Dennis Williamson