2016-07-15 35 views
0

我想改变这样的文字:使用awk来一列选择性地改变语序

Fred Flintstone:father:male 
Wilma Flintstone:mother:female 
Flintstone, Pebbles:daughter:female 
Barney Rubble:father:male 
Rubble, Betty:mother:female 
Bam Bam Rubble:son:male 

到:

Flintstone, Fred:father:male 
Flintstone, Wilma:mother:female 
Flintstone, Pebbles:daughter:female 
Rubble, Barney:father:male 
Rubble, Betty:mother:female 
Rubble, Bam Bam:son:male 

是否有可能做到这一点在awk中的一行?或者更好地提取第一列操纵文本并重新导入列?

+2

是的,它绝对有可能在一行awk :)你有没有尝试过任何东西? –

回答

1

这里是徒劳无功一个衬里:

awk -F: '$1=gensub(/([^,]+)[ ]+([^ ,]+)/,"\\2, \\1","1",$1)' yourfile 
  • 它使用:-F选项
  • gensub函数是在图案部分使用上$1定界符:
    • 如果一个替代是可能的,表达是真实的,并修改$1
      • 隐式使用默认操作打印。
    • 如果表达式不匹配(由于$1逗号)行被隐式印刷
+0

我必须指出,gensub是一个gnu awk扩展。 –

0

不限 awk程序可以是一个线。不用分号做它更难。

我想出了以下内容:

BEGIN { FS = ":" } 

$1 !~ /,/ { 
    match($1,/[^ ]+$/) 
    n = RSTART 
    name = substr($1, n+1) ", " substr($1, 1, n-1) 
    gsub(/^[^:]+/, name) 
    print 
    next 
} 

{ print } 

我认为这是标准的awk。它不依赖于反向引用,也不依赖于match()返回任何东西。

0
$ cat tst.awk 
BEGIN { FS=OFS=":" } 
{ 
    rest = last = $1 
    sub(/.*[ ,]/,"",last) 
    sub(/[ ,]+[^ ]+$/,"",rest) 
    $1 = last ", " rest 
    print 
} 

$ awk -f tst.awk file 
Flintstone, Fred:father:male 
Flintstone, Wilma:mother:female 
Pebbles, Flintstone:daughter:female 
Rubble, Barney:father:male 
Betty, Rubble:mother:female 
Rubble, Bam Bam:son:male