Daniel
Daniel

Reputation: 2592

AWK remove leading and trailing whitespaces from fields

I need to remove leading and trailing whitespace characters from an input like this below using awk:

27 mA; 25 mA   ; 24 mA ; 22 mA;

Required output:

27 mA;25 mA;24 mA;22 mA;

What I've tried:

  1. awk -F";" '{$1=$1}1': doesn't remove the whitespaces, but removes ;s
  2. awk -F";" '{gsub(/^[ \t]+|[ \t]+$/,""); print;}': doesn't remove the whitespaces

How can I modify these commands above to remove all leading and trailing whitespace (0x20) characters?

Update

Input might contain leading whitespace(s) at the first field:

  27 mA; 25 mA   ; 24 mA ; 22 mA;

Upvotes: 2

Views: 1747

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133428

With your shown samples, please try following awk code. Written and tested with GNU awk, should work in any awk.

awk -F'[[:space:]]*;[[:space:]]*' -v OFS=";" '{sub(/^[[:space:]]+/,"");$1=$1} 1' Input_file

OR

awk -F'[[:blank:]]*;[[:blank:]]*' -v OFS=";" '{sub(/^[[:blank:]]+/,"");$1=$1} 1' Input_file

Explanation: Simple explanation would be, making field separator for each line as spaces(0 or more occurrences) followed by ; which is further followed by 0 or more occurrences of spaces. Setting OFS as ;. In main program, re-assigning 1st field, then simply printing line.

2nd solution: As per @jhnc nice suggestion in comments, you could try with your shown samples.

awk '{sub(/^[[:space:]]+/,"");gsub(/ *; */,";")} 1' Input_file

Upvotes: 3

anubhava
anubhava

Reputation: 784958

A simple sed:

sed -E 's/[[:blank:]]*;[[:blank:]]*/;/g; s/^[[:blank:]]+|[[:blank:]]+$//' file

27 mA;25 mA;24 mA;22 mA;

or this awk:

awk '{gsub(/[[:blank:]]*;[[:blank:]]*/, ";"); gsub(/^[[:blank:]]+|[[:blank:]]+$/, "")} 1' file

Upvotes: 2

Related Questions