我有一个脚本 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
而不是 awk,我用 while 来解决问题:
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
循环时缓慢的猛击:
(
# ignore first line
IFS= read -r line;
printf "%sn" "$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:%sn" "$line" "$(get_alias "$ip")"
done
) < test.sh
脚本从字面上看:- 读取第一行并输出它而不进行更改- 然后当它从文件中读取行时- 我们从行中获取 IP 地址作为 4 字段(awk '{print $4}'
和类似的字段也可以)- 然后我们打印带有 get_alias
函数输出的行。