从awk中的字符串修剪前导和尾随空格 [英] Trim leading and trailing spaces from a string in awk

查看:123
本文介绍了从awk中的字符串修剪前导和尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除以下input.txt的第二列中的前导和尾随空格:

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

Name, Order  
Trim, working
cat,cat1

Name, Order  
Trim, working
cat,cat1

我已经使用下面的awk删除了第二列中的前导和尾随空格,但是它不起作用.我想念什么?

I have used the below awk to remove leading and trailing space in 2nd column but it is not working. What am I missing?

awk -F, '{$2=$2};1' input.txt

这给出的输出为:

Name, Order  
Trim, working
cat,cat1

Name, Order  
Trim, working
cat,cat1

前导空格和尾随空格均未删除.

Leading and trailing spaces are not removed.

推荐答案

如果仅在带有逗号的行中修剪所有空格,并使用awk,则以下内容将为您工作:

If you want to trim all spaces, only in lines that have a comma, and use awk, then the following will work for you:

awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt

如果只想删除第二列中的空格,请将表达式更改为

If you only want to remove spaces in the second column, change the expression to

awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt

请注意,gsub用第二个表达式替换//中的字符,在第二个表达式中,该变量是第三个参数-并使用in-place-换句话说,完成后,用$0(或$2)已被修改.

Note that gsub substitutes the character in // with the second expression, in the variable that is the third parameter - and does so in-place - in other words, when it's done, the $0 (or $2) has been modified.

完整说明:

-F,            use comma as field separator 
               (so the thing before the first comma is $1, etc)
/,/            operate only on lines with a comma 
               (this means empty lines are skipped)
gsub(a,b,c)    match the regular expression a, replace it with b, 
               and do all this with the contents of c
print$1","$2   print the contents of field 1, a comma, then field 2
input.txt      use input.txt as the source of lines to process

编辑我想指出@BMW的解决方案更好,因为它实际上是使用两个连续的gsub命令修剪前导和尾随空格的.在赞扬的同时,我将解释其运作方式.

EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub commands. Whilst giving credit I will give an explanation of how it works.

gsub(/^[ \t]+/,"",$2);    - starting at the beginning (^) replace all (+ = zero or more, greedy)
                             consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)}    - do the same, but now for all space up to the end of string ($)
1                         - ="true". Shorthand for "use default action", which is print $0
                          - that is, print the entire (modified) line

这篇关于从awk中的字符串修剪前导和尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆