Reputation: 2592
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:
awk -F";" '{$1=$1}1'
: doesn't remove the whitespaces, but removes ;
sawk -F";" '{gsub(/^[ \t]+|[ \t]+$/,""); print;}'
: doesn't remove the whitespacesHow can I modify these commands above to remove all leading and trailing whitespace (0x20) characters?
Input might contain leading whitespace(s) at the first field:
27 mA; 25 mA ; 24 mA ; 22 mA;
Upvotes: 2
Views: 1747
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
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