繁体   English   中英

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

[英]How to do something like this in linux shell script

我有一个正在执行某些操作的 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 中用字符串替换这些空格。

任何线索表示赞赏。

谢谢

使用条件运算符:

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()
}'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM