I have a CSV that looks like this:
things,ID,hello_field,more things
stuff,123 ,hello ,more stuff
stuff,123 ,hello ,more stuff
stuff ,123 ,hello ,more stuff
stuff,123 ,hello ,more stuff
stuff ,123,hello ,more stuff
stuff,123,hello ,more stuff
stuff ,123,hello ,more stuff
How can I remove leading and trailing whitespace from all columns except for the second (ID
)? The final output would look like this:
things,ID,hello_field,more things
stuff,123 ,hello,more stuff
stuff,123 ,hello,more stuff
stuff,123 ,hello,more stuff
stuff,123 ,hello,more stuff
stuff,123,hello,more stuff
stuff,123,hello,more stuff
stuff,123,hello,more stuff
I tried using the following regex, but it removes spaces from all fields, including those in the ID
column.
s/( +,|, +)/,/gi;
Split, trim selectively, rejoin
perl -F, -lane 's/^\s+|\s+$//g for @F[0,2..$#F]; print join ",", @F' file.csv
Switches:
-F/pattern/
: split()
pattern for -a
switch (//
's are optional)-l
: Enable line ending processing-a
: Splits the line on space and loads them in an array @F
-n
: Creates a while(<>){...}
loop for each line in your input file.-e
: Tells perl
to execute the code on command line.Code:
EXPR for @F[0,2..$#F]
: Iterate over array slice (skipping 2nd field)s/^\s+|\s+$//g
: Remove leading and trailing spaces from fieldsprint join ",", @F
: Print the resultsCollected from the Internet
Please contact [email protected] to delete if infringement.
Comments