Trim leading and trailing spaces from a string in awk

后端 未结 8 876
离开以前
离开以前 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 02:00

    I just came across this. The correct answer is:

    awk 'BEGIN{FS=OFS=","} {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2)} 1'
    
    0 讨论(0)
  • 2020-12-01 02:02

    If it is safe to assume only one set of spaces in column two (which is the original example):

    awk '{print $1$2}' /tmp/input.txt

    Adding another field, e.g. awk '{print $1$2$3}' /tmp/input.txt will catch two sets of spaces (up to three words in column two), and won't break if there are fewer.

    If you have an indeterminate (large) number of space delimited words, I'd use one of the previous suggestions, otherwise this solution is the easiest you'll find using awk.

    0 讨论(0)
提交回复
热议问题