Trim leading and trailing spaces from a string in awk

后端 未结 8 873
离开以前
离开以前 2020-12-01 01:04

I\'m trying to remove leading and trailing space in 2nd column of the below input.txt:

Name, Order  
Trim, working

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 01:57

    Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).

    I would use sed:

    sed 's/, /,/' input.txt
    

    This will remove on leading space after the , . Output:

    Name,Order
    Trim,working
    cat,cat1
    

    More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,:

    sed 's/,[ \t]\?/,/g' input.txt
    

    It will also work with more than two columns because of the global modifier /g


    @Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:

    sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt
    

    *EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *


    IMO sed is the optimal tool for this job. However, here comes a solution with awk because you've asked for that:

    awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt
    

    Another simple solution that comes in mind to remove all whitespaces is tr -d:

    cat input.txt | tr -d ' '
    

提交回复
热议问题