How to Remove Leading Spaces from a File in Linux Using sed

Introduction

Spaces at the beginning of words or lines in a file can sometimes cause formatting issues or make it difficult to process the file correctly. Linux provides several commands that can be used to remove unwanted spaces. In this guide, we will use cut, sort, and sed commands to remove spaces from the beginning of words and display the cleaned output.

Prerequisites

Before proceeding, make sure you have:

  • Access to a Linux server or system.
  • Basic knowledge of Linux commands.
  • A file containing the text that needs to be processed.
  • Permission to read the input file and write to the output file, if required.

Implementation

This is a simple script to show how to remove a space in 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 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 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 this 
 cat filename |cut -d”:” -f2 |sort | sed -e ‘s/^[ \t]*//’ > filename.txt

Conclusion

Using the cut, sort, and sed commands, you can easily remove unwanted spaces from the beginning of words or lines in a file. The commands can also be combined with output redirection (>) to save the processed content into a new file for further use.

FAQs

1. How do I remove leading spaces from a file?
Use sed 's/^[ \t]*//' filename.

2. Can I save the output to another file?
Yes, use > filename.txt at the end of the command.

3. Will this remove spaces between words?
No, it removes only spaces or tabs at the beginning of each line.

How to Create and remove a Symbolic Link in Linux

How to convert file system type from ext3 to ext4 for Linux servers

Talk to our experts

Looking for the right technology solution for your business?. Our experts can help with web hosting, domain registration, DevOps and cloud, software development, web applications, mobile applications, and enterprise solutions. Get in touch with our team here.

admin

Writes about Containers & Kubernetes at Pheonix Solutions.

Leave a Reply

Scroll to Top