Linux 如何从 awk 中的变量中修剪空白?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9985528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:34:18  来源:igfitidea点击:

How can I trim white space from a variable in awk?

linuxbashshellawk

提问by Hoa

Suppose $2 is my variable. I have tried going from

假设 $2 是我的变量。我试过从

awk -F\, '{print  ":"}'

to

awk -F\, '{print gsub(/[ \t]+$/, "", ) ":"}'

But it goes from printing something to printing nothing at all.

但它从打印一些东西到什么都不打印。

采纳答案by je4d

You're printing the result of the gsub, but gsubdoes an in-place modify of $2instead of returning a modified copy. Call gsub, then print:

您正在打印 的结果gsub,但gsub会进行就地修改,$2而不是返回修改后的副本。调用gsub,然后打印:

awk -F\, '{gsub(/[ \t]+$/, "", ); print  ":"}'

回答by JGC

(I don't have enough points to comment on the previous answer directly.)

(我没有足够的分数直接评论上一个答案。)

To trim whitespace at the endof $2use:

在使用结束时修剪空格$2

awk -F\, '{gsub(/[ \t]+$/, "", ); print  ":"}'

To trim whitespace at the beginningof $2use:

要在修剪空白开始$2使用:

awk -F\, '{gsub(/^[ \t]+/, "", ); print  ":"}'

And for both end and beginning:

对于结束和开始:

awk -F\, '{gsub(/^[ \t]+/, "", ); gsub(/[ \t]+$/, "", ); print  ":"}'

回答by Jong Bor Lee

These functions come in handy to improve readability. They also return the trimmed result:

这些功能可以派上用场,以提高可读性。他们还返回修剪后的结果:

function ltrim(s) { sub(/^[ \t\r\n]+/, "", s); return s }
function rtrim(s) { sub(/[ \t\r\n]+$/, "", s); return s }
function trim(s) { return rtrim(ltrim(s)); }
BEGIN {
# whatever
}
{
# whatever
}
END {
# whatever
} 

Source: https://gist.github.com/andrewrcollins/1592991

来源:https: //gist.github.com/andrewrcollins/1592991

回答by Ben

A one liner for gawk:

Gawk 的单衬:

gawk -F\, '{ = gensub(/^[ \t]*|[ \t]*$/,"","g",)}'

回答by VIPIN KUMAR

ltrim and rtrim in Unix

Unix 中的 ltrim 和 rtrim

awk 'BEGIN{FS=OFS="|"} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' filename.txt

awk 'BEGIN{FS=OFS="|"} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' filename.txt

回答by DAVID ALEJANDRO PINEDA

A more simple option:

一个更简单的选择:

You have to define the trim function, the use gsub for a general replacement. Then find with a regex if starts or ends with space(one or more times), returns the field.

您必须定义修剪功能,使用 gsub 进行一般替换。如果以空格开头或结尾(一次或多次),则使用正则表达式查找,返回该字段。

   awk -F'|' 'function trim(field){
   gsub(/^ +| +$/,"", field); 
   return field
   }{
   OFS=",";
   print trim(),trim()}' stations > lista.csv

With this code is enougth

有了这个代码就够了

And the file stationsis with this structure:

文件具有以下结构:

     1 | UTAR | U de Tarapacá                   
     3 | VALN | Valparaíso                      
     4 | JRGN | Junta Gorgino                   
     6 | TRPD | Torpederas