将命令输出附加到文件的每一行

时间:2019-01-08 22:23:02

标签: linux bash

我有一个脚本test.sh

#!/bin/bash
route add -net <IP1> netmask 0.0.0.0 gw 10.xx.xx.1 dev eth0
route add -net <IP2> netmask 0.0.0.0 gw 10.xx.xx.1 dev eth0

我在另一个脚本中创建了一个函数get_alias,该函数获取对应于IP地址的别名值。

我想将对应ip的get_alias命令输出附加到test.sh的每一行(最顶部除外)

所以假设

$(get_alias IP1)为1,$(get_alias IP2)为2

所以我想要的文件应该如下:

#!/bin/bash
route add -net <IP1> netmask 0.0.0.0 gw 10.xx.xx.1 dev eth0:1
route add -net <IP2> netmask 0.0.0.0 gw 10.xx.xx.1 dev eth0:2

我在awk以下尝试过,但这不起作用

awk  '{ print $0":"$(get_alias "$4") }' test.sh 

2 个答案:

答案 0 :(得分:2)

我使用awk代替awk解决了该问题:

while read -r line ; do
    ip=$(echo $line | cut -d " " -f 4)
    alias="$(get_alias "$ip")"
    echo "$line:$alias"
done < test.sh > test_out.sh

答案 1 :(得分:1)

慢速bash循环:

(
    # ignore first line
    IFS= read -r line; 
    printf "%s\n" "$line";
    # for the rest of the lines
    while IFS= read -r line; do
         # get the ip address
         IFS=$' \t' read _ _ _ ip _ <<<"$line"
         # output the line with `:` with the output of get_alias:
         printf "%s:%s\n" "$line" "$(get_alias "$ip")"
    done
) < test.sh

脚本实际上是: -读取第一行并将其输出而不进行更改 -然后从文件中读取行 -我们从该行获得的IP地址为4字段(awk '{print $4}'和类似的地址也可以使用) -然后我们使用get_alias函数的输出来打印行。

相关问题