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

标签 linux bash shell awk

我有一个正在执行某些操作的 shell 脚本。我想打印输出中存在空格的 Unknown 字符串。

我想检查是否(f[1] == "")或(f[2] == "")或(f[3] == ""),它应该被未知字符串替换并且应该写入单个文件

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

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

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

关于linux - 如何在Linux shell脚本中做这样的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829257/

相关文章:

node.js - NodeJS exec/spawn stdout 在 8192 个字符处切断流

c++ - 在 Mac 上编译 C++ 程序在 Linux 上运行

c++ - 同一程序在 Windows 和 Linux 上的行为不同

linux - bash while循环不退出也不回显

bash - bash 中的序列扩展和变量

java - 如何从 Java 应用程序执行命令?

c++ - 如何将输出重新路由到带有时间戳的文件?

linux - 删除 dos 行尾并再次加入行备份的最佳工具

windows - 环境 : bash\r: No such file or directory

linux - 在 Bash 脚本中传递变量名称和值