Home > awk, bash, sed > bash – Trimming spaces from variables.

bash – Trimming spaces from variables.

I was reading “settings” from a tab separated text file. The values I was getting had extra white spaces that were not needed. I needed to strip them out. Here is the sample of the text file I was using.

cat sample_file
this | is a sample |   file with |    unwanted spaces   | 

After a quick search on google I got a few solutions. Here is what worked for me.

1. sed

cut -d"|" -f4 sample_file | sed 's/^ \+\| \+$//g'

2. awk

cut -d"|" -f4 sample_file | awk '{gsub(/^ +| +$/,"")}1'


Categories: awk, bash, sed Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: