shell script to trim whitespace

Shell Script to Trim Whitespace

Often you may need to trim whitespace in one or more files on your system. It can be tedious to manually remove whitespaces if you have large files. So it is better to use a shell script for this purpose. In this article, we will look at how to create shell script to trim whitespace in Linux. You can use this script in all Linux distributions since its commands are available in every Linux.


Shell Script to Trim Whitespace

Here are the steps to create shell script to trim whitespace.


1. Create empty shell script

Open terminal and run the following command to create an empty shell script.

$ sudo vi trim_whitespace.sh


2. Add shell script

Add the following lines to your shell script

#!/bin/sh


sudo awk '{$1=$1;print}'

Save and close the file. In the above code, we first define shell script execution environment. Then we use awk command to trim whitespaces and print the output.

This script will trim leading and trailing spaces, and compress consecutive tabs and spaces into single space.

If you also want to remove blank lines from your file, replace the awk command above with the following.

sudo awk '{$1=$1};NF'


3. Make shell script executable

Run the following command to make shell script executable.

$ sudo chmod +x trim_whitespace.sh


4. Run shell script

If you have a text file /home/data.txt then run the above shell script as shown below, passing full path to file as command line argument.

$ sudo ./trim_whitespace.sh /home/data.txt


5. Automate Shell Script

If you want to regularly run this script on a file to automatically trim whitespaces in it, then simple create a cronjob for it. Open crontab with the following command.

$ crontab -e

Add the following lines to it.

0 10 * * * ./trim_whitespace.sh /home/data.txt >/dev/null 2>&1

The above code will run your script every day at 10.a.m and send error/output to /dev/null. This kind of cronjob is useful if your file updates regularly at the same location and you want to trim whitespaces in it.


That’s it. As you can see it is very easy to setup a shell script to remove whitespaces from your files. You may also use sed command instead of awk in your shell script.

Also read:

How to Disable HTTP TRACE Method in Apache Server
How to Switch User in Ubuntu Linux
How to Bring Background Process to Foreground
LS File Size in kb, Mb
How to Get User Input in Shell Script

Leave a Reply

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