使用awk有选择地更改列中的单词顺序

时间:2016-07-15 20:46:06

标签: 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中执行此操作?或者,提取第一列是否更好地操作文本并重新导入列?

3 个答案:

答案 0 :(得分:1)

这是一个gawk one liner:

:
  • 它使用-F分隔符与gensub选项
  • $1函数用于模式部分中的$1
    • 如果可以替换,则表达式为true并修改$1
      • 隐式使用默认操作print。
    • 如果表达式不匹配(由于{{1}}中的逗号),则隐式打印该行

答案 1 :(得分: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()返回任何东西。

答案 2 :(得分: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