在Solaris上的awk中使用多字符字段分隔符

时间:2014-12-10 11:26:42

标签: bash shell awk solaris

我希望在awk中使用字符串(BIRCH)作为字段分隔符来打印第二个字段。我正在尝试以下命令:

cat tmp.log|awk -FBirch '{ print $2}'

以下输出正在打印:

  

irch2014 / 06 / 23,04:36:45,3,1401503,XML-哈伦,P12345-1,温度,0a653356353635635,温度,L,成功

期望的输出:

  

2014/06 / 23,04:36:45,3,1401503,XML-哈伦,P12345-1,温度,0a653356353635635,温度,L,成功

tmp.log 文件的内容。

-bash-3.2# cat tmp.log  
Dec 05 13:49:23 [x.x.x.x.180.100] business-log-dev/int [TEST][0x80000001][business-log][info] mpgw(Test): trans(8497187)[request][10.x.x.x]:
Birch2014/06/23,04:36:45,3,1401503,xml-harlan,P12345-1,temp,0a653356353635635,temp,L,Success

我做错了吗?

  • 操作系统:Solaris10
  • Shell:Bash

尝试下面的一个ansers中建议的命令。我得到了所需的输出,但顶部有一个额外的空行。如何从输出中消除它?

-bash-3.2# /usr/xpg4/bin/awk -FBirch '{print $2}' tmp.log

2014/06/23,04:36:45,3,1401503,xml-harlan,P12345-1,temp,0a653356353635635,temp,L,Success

2 个答案:

答案 0 :(得分:3)

最初,我建议在“Birch”(-F'Birch')周围加上引号,但实际上,我认为这不应该有任何区别。

我根本没有使用Solaris的经验,但您可能还想尝试使用nawk(“new awk”)而不是awk

nawk -FBirch '{print $2}' file

如果这样做,您可能需要考虑创建一个别名,以便始终使用具有更多功能的较新版本的awk。

您可能还想尝试在/usr/xpg4/bin目录中使用awk版本,这是一个符合POSIX标准的实现,因此应该支持多字符FS

/usr/xpg4/bin/awk -FBirch '{print $2}' file

如果您只想打印包含多个字段的行,则可以添加条件:

/usr/xpg4/bin/awk -FBirch 'NF>1{print $2}' file

只有在有多个字段时才打印第二个字段。

答案 1 :(得分:1)

来自solaris usr/bin/awk

上默认awk的手册页
-Fc            Uses the character c as the  field  separator
               (FS)  character.   See  the  discussion of FS
               below.

如您所见,solaris awk只将一个字符作为字段分隔符

同样在手册页中分割

split(s, a, fs)

     Split the string s into array elements a[1],  a[2],  ...
     a[n],  and  returns  n.  The separation is done with the
     regular expression fs or with the field separator FS  if
     fs is not given.

正如你在这里看到的,它需要一个正则表达式作为分隔符,所以我们可以使用。

awk 'split($0,a,"Birch"){print a[2]}' file

打印按Birch

分割的第二个字段
相关问题