删除前导和AWK现场尾随空间 [英] Remove Leading and trailing space in field in awk

查看:218
本文介绍了删除前导和AWK现场尾随空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图除去开头和结尾中的以下 2列空间input.txt的

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

名称,顺序结果
修剪,工作结果
猫,CAT1

我用下面的 AWK 删除领先,并在第2列尾随空格,但AWK不工作。我缺少什么?

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

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

这使输出为:

名称,顺序结果
修剪,工作结果
猫,CAT1

首尾空格不会被删除。

推荐答案

如果要修剪所有空格,只有在有一个逗号线,并使用 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

如果你只是想在第二列中删除空格,改变前pression到

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 替换的字符在 // 与第二前pression,在变量这是第三个参数 - 和就地这样做 - 换句话说,当它完成时, $ 1,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

修改我想指出的是,@宝马的解决方案是更好,因为它实际上剪裁只领先并用两个连续的 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天全站免登陆