AWK将null列替换为下一行的列值

时间:2016-02-05 23:11:10

标签: shell awk

我有以下缺少列值的示例文件,我想用同一列中的下一个可用值替换它。

    var QuadForm;
QuadForm = function () {
    this.getName = function () {
        // search through the global object for a name that resolves to this object
        for (var name in window)
            if (window[name] == this) {
                window[name] = this;
                window[window[name]] = window[name];
                myObjectName= name;
                break;
            }
    },
        this.initForm = function (parms) {

            this.getName()

            $.extend(this, parms);
            if (window.myState) {
                delete window.myState;
            }
            this.containerId = parms.formId;
            this.getForm(parms);
            this.workflowLabels('hide');

以下是我要做的事情:

cat test.txt
11.2.0.1,ORA1,ORACLE
11.2.0.4,ORA2,ORACLE
11.2.0.3,ORA3,ORACLE
12.2.0.1,ORA4,ORACLE
,ORA5,ORACLE
,ORA6,ORACLE
12.2.0.2,ORA7,ORACLE
,MYS1,MYSQL
5.1,MYS2,MYSQL

预期产出:

 cat test.txt |awk '{printf("%s,%s,%s\n", $11,$3,$1);}'|awk -F',' 'BEGIN{OFS=","}
   {
        for (i=1; i<=NF; i++)
        if ($i=="")
            --Read next column value
            --If next column is null, read futhur next
            -- Assign next available value to $i
        print
    }'

由于

2 个答案:

答案 0 :(得分:3)

你可以这样做:

awk -F, '$1==""{a[n++]=$0;next} n{for (i=0;i<n;i++) print $1 a[i]; n=0} 1' file

细节:

$1=="" {          # if the first field is empty
    a[n++]=$0     # store the whole line at index n and increment n
    next          # jump to the next line
}

n {                    # if n isn't zero
    for (i=0;i<n;i++)  # loop over stored lines indexes
        print $1 a[i]  # and print lines starting with the current first field
    n=0                # set n to 0
}

1  # true, print the current line

答案 1 :(得分:2)

使用awk

tac file | awk -F, '$1{l=$1} !$1{$1=l} OFS=","' | tac
  • taccat类似,但逐行撤消文件。
  • awk -F,将字段分隔符设置为逗号。
  • $1{l=$1}如果设置了第一个字段$1,请设置l变量并打印该行
  • !$1{$1=l}如果未设置第一个字段$1,请从l变量中取值并打印该行。
  • OFS=","将输出字段分隔符设置为逗号。
  • tac最终将文件反转。

输出:

11.2.0.1,ORA1,ORACLE
11.2.0.4,ORA2,ORACLE
11.2.0.3,ORA3,ORACLE
12.2.0.1,ORA4,ORACLE
12.2.0.2,ORA5,ORACLE
12.2.0.2,ORA6,ORACLE
12.2.0.2,ORA7,ORACLE
5.1,MYS1,MYSQL
5.1,MYS2,MYSQL