如何在使用值打印时删除awk空间

  • 本文关键字:删除 awk 空间 打印 awk
  • 更新时间 :
  • 英文 :


我有一个test.csv

#cat test.csv
a.b.c.d
a.b
a.b.c
a-a.b.c          
a-a.b

(1( 我正在尝试打印第一个点之后的所有值,(2(最后一个点不能打印。

我在下面尝试了一下,但它出现了空格,实际文件大约有10亿条记录,不知道如何在没有点的情况下打印,

#cat test.csv | awk -F. '{print $2,".",$3}' 
b . c
b . 
b . c
b . c
b . 

所需输出

b.c.d
b
b.c
b.c          
b

输出中的空格是因为您告诉awk添加空格。print语句中的每个,都是告诉awk在输出中的那个位置添加OFS变量的值(默认情况下是一个空白字符(。代替:

awk -F. '{print $2,".",$3}'

尝试以下任一项:

awk -F. '{print $2"."$3}'
awk 'BEGIN{FS=OFS="."} {print $2,$3}'

要获得你想要的输出awk将是:

awk '{sub(/[^.]*./,"")}1'

但我真的建议你使用为这项任务设计的工具,剪切:

cut -d'.' -f2-
$ sed 's|[^.]*.||' test.csv
b.c.d
b
b.c
b.c
b

[^.]的意思不是.字符。..字符(需要转义,因为它在正则表达式中有特殊含义(。

请您尝试以下内容,并使用所示的示例进行编写和测试。

awk 'BEGIN{FS=OFS="."} NF>=3{print $2,$3;next} NF==2{print $2}' Input_file

解释:添加对上述代码的详细解释。

awk '                ##Starting awk program from here.
BEGIN{               ##Starting BEGIN section of this awk program from here.
FS=OFS="."         ##Setting FS and OFS as DOT(.) here.
}
NF>=3{               ##Checking condition if number of fields greater than 3 then do following.
print $2,$3        ##Printing 2nd and 3rd field values here.
next               ##next will skip all further statements from here.
}
NF<=2{               ##Checking if number of fields is lesser than 2 then do following.
print $2           ##Printing 2nd field here.
}
' Input_file         ##Mentioning Input_file name here.

最新更新