Introduction

When working with configuration files, scripts, log files, or text documents, you may encounter unwanted leading spaces before specific words. These extra spaces can affect formatting, cause parsing issues, or result in errors in scripts and configuration files. Linux provides several command-line utilities, such as sed, awk, and perl, to efficiently remove leading spaces from words or lines. This guide explains how to remove a space in front of a word within a file while preserving the rest of the file’s content.

Prerequisites

Before proceeding, ensure the following:

  • Access to a Linux system with terminal access.
  • Appropriate read and write permissions for the target file.
  • A backup of the file before making modifications (recommended).
  • Basic familiarity with Linux command-line operations.
  • Standard text-processing utilities such as sed, awk, or perl installed on the system

IMPLEMENTATION


This is a simple script to show how to remove space in a front of a word from a file. You can learn about this simple command for removing the space in front of a word and execute it from your end. I was trying to do this using various commands and scripts. but I was unsuccessful in doing it. Later, I just used a simple method to remove the space in front of a word in a file. I’m very happy to share the same with you.


Just use this command to remove the space in front.

cat filename |cut -d”:” -f2 |sort | sed -e ‘s/^[ \t]*//’
 
cat filename – This will show you all the contents in a file name
 
# cat filename
  arun
 hemanth
     :karthick
madhan
  Dhanasekar
 
cut -d”:” -f2 – this will remove : if there are any before a word. -f2 is field 2
sort – sorting the output in a order
sed -e ‘s/^[ \t]*//’
 
# cat c |cut -d”:” -f2 |sort | sed -e ‘s/^[ \t]*//’
arun
Dhanasekar
hemanth
karthick
madhan

Now it will show you the output. If you want the output added inside a file just use tfromhis 

 
 cat filename |cut -d”:” -f2 |sort | sed -e ‘s/^[ \t]*//’ > filename.txt
 

Conclusion

Removing unwanted spaces from a file helps maintain consistent formatting and prevents issues in scripts, configuration files, and text processing tasks. By using Linux text-processing utilities, you can quickly remove leading spaces from specific words or entire lines with minimal effort. After making the changes, it is recommended to verify the file’s contents to ensure the formatting is correct and no unintended modifications have been introduced.

Leave a Reply