如何在linux shell脚本中做这样的事情

时间:2014-04-03 06:12:19

标签: linux bash shell awk

我有一个正在做某事的shell脚本。我想打印输出中有空格的Unknown字符串。

我想检查(f[1] == "") or (f[2] == "") or (f[3] == ""),是否应该用unknown字符串替换它,并且应该写在一个文件中

 if(f[1] == "") printf(fmt, id, f[1], f[2], f[3]) > file

其中f[1],f[2],f[3]如果为空,则应替换为unknown字符串

其中f[1]是第一个索引,fmt是我在代码中定义的格式说明符。如何在Linux中用字符串替换这些空格。

任何领导都表示赞赏。

由于

1 个答案:

答案 0 :(得分:1)

使用条件运算符:

ec2-describe-instances | awk -F'\t' -v of="$out" -v mof="$file" '
function pr() { # Print accumulated data
    if(id != "")    {   # Skip if we do not have any unprinted data.
        printf(fmt, id, f[1], f[2], f[3]) > of
        if (f[1] == "" || f[2] == "" || f[3] == "") {
            printf(fmt, id, f[1]==""?"Unknown":f[1], f[2]==""?"Unknown":f[2], f[3]==""?"Unknown":f[3]) > mof
        }
    }
    # Clear accumulated data.
    id = f[1] = f[2] = f[3] = ""
}

BEGIN { # Set the printf() format string for the header and the data lines.
    fmt = "%-20s %-40s %-33s %s\n"
    # Print the header
    headerText="Instance Details"
    headerMaxLen=100
    padding=(length(headerText) - headerMaxLen) / 2
    printf("%" padding "s" "%s" "%" padding "s"  "\n\n\n", "", headerText, "") > of
    printf(fmt, "Instance id", "Name", "Owner", "Cost.centre") > of
    printf("%" padding "s" "%s" "%" padding "s"  "\n\n\n", "", headerText, "") > mof
    printf(fmt, "Instance id", "Name", "Owner", "Cost.centre") > mof
}
$1 == "TAG" {
    # Save the Instance ID.
    id = $3
    if($4 ~ /[Nn]ame/) fs = 1           # Name found
    else if($4 ~ /[Oo]wner/) fs = 2         # Owner found
    else if($4 ~ /[Cc]ost.[Cc]ent[er][er]/) fs = 3  # Cost center found
    else next                   # Ignore other TAGs
    f[fs] = $5  # Save data for this field.
}
$1 == "RESERVATION" {
    # First line of new entry found; print results from previous entry.
    pr()
}
END {   # EOF found, print results from last entry.
    pr()
}'