home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 25.12 Double Space, Triple Space ... Chapter 25
Showing What's in a File
Next: 25.14 How to Look at the End of a File: tail
 

25.13 pushin: Squeeze Out Extra White Space

If you're viewing or printing a file with lines that are too long to read, you can use a program like fold ( 43.8 ) to fold the lines. Or, if there's lots of white space in each line - multiple spaces and/or TABs next to each other - you can use the script at the end of this article. The pushin script replaces series of spaces and/or TABs with a single space, "pushing in" each line as much as it can. It reads from files or standard input and writes to standard output.

Here's an example of lines in a file that aren't too long (we can't print long lines in this book, anyway) but that do have a lot of white space. Imagine how pushin would help with longer lines:

% 

cat data


resistor           349-4991-02                  23
capacitor          385-2981-49                  16
diode              405-3951-58                   8
% 

pushin data


resistor 349-4991-02 23
capacitor 385-2981-49 16
diode 405-3951-58 8

Here's the script:


#!/bin/sed -f
s/[  ][   ]*/ /g

Inside each pair of brackets, [ ] , the sed substitute command has a space and a TAB. The replacement string is a single space.

That file doesn't use a shell; the kernel starts sed directly ( 45.3 ) and gives it the script itself as the input file expected with the -f option. If your UNIX can't execute files directly with #! , type in this version instead:

exec sed 's/[     ][      ]*/ /g' ${1+"$@"}

It starts a shell, then exec replaces the shell with sed ( 45.7 ) . The ${1+"$@"} works around a problem with argument handling ( 46.7 ) in some Bourne shells.

- JP


Previous: 25.12 Double Space, Triple Space ... UNIX Power Tools Next: 25.14 How to Look at the End of a File: tail
25.12 Double Space, Triple Space ... Book Index 25.14 How to Look at the End of a File: tail

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System