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

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"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
5 comments… add one
  • Proactiveaditya Mar 7, 2010 @ 18:42

    echo “eth0 192.168.12.2″|awk ‘{print $2}’

    • Anonymous Apr 29, 2010 @ 6:38

      sed -e ‘s/[\t ]//g;/^$/d’ $file

      It also delete t character if given in file.

      • Anonymous Dec 2, 2010 @ 12:44

        How does it remove double space?

  • siva Aug 26, 2009 @ 12:10

    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

    • Joe Dec 7, 2010 @ 5:00

      echo “eth0 192.168.12.2″ | cut -d” ” -f2

      will work as well

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.