Sed Shell Script To Remove All Blank Spaces From a Text File

in Categories File-management last updated September 16, 2008

sed (Stream EDitor) a Unix utility which parses text files and implements a programming language which can apply textual transformations to such files. It reads input files line by line (sequentially), applying the operation which has been specified via the command line (or a sed script), and then outputs the line.

The following example shows a typical use of sed:

#!/bin/bash
# Write a shell script which reads the contents in a text file and removes 
# all the blank spaces in them and redirects the output to a file.
# -------------------------------------------------------------------------
# Copyright (c) 2001 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
out="output.$$"
echo -n "Emter a file name : "
read file
 
if [ ! -f $file ]
then
	echo "$file not a file!"
	exit 1
fi
 
sed -e 's/[\t ]//g;/^$/d' $file > $out
echo "Output written to $out file"

Share this on:

5 comment

  1. Thanks, Very useful script.. How to remove a particular word say etho

    eth0 192.168.12.2
    eth0 192.168.1.41

    want to remove eth0 from above line

    Have a question? Post it on our forum!