[英]Append command output to each line of a file
I have a script test.sh 我有一个脚本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
I have created a function get_alias in another script which gets alias value corresponds to ip address. 我在另一个脚本中创建了一个函数get_alias,该脚本获取别名值对应于ip地址。
I want to append the get_alias command output of corresponding ip to each line (except top most) of test.sh 我想将对应ip的get_alias命令输出附加到test.sh的每一行(最顶部除外)
So suppose if 所以假设
$(get_alias IP1) is 1 and $(get_alias IP2) is 2 $(get_alias IP1)为1和$(get_alias IP2)为2
So my desired file should be as below: 所以我想要的文件应该如下:
#!/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
I have tried below awk but this is not working 我在awk下尝试过,但这不起作用
awk '{ print $0":"$(get_alias "$4") }' test.sh
Instead of awk i have used while to resolve the issue: 我已经用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
A slow bash while loop: 慢bash while循环:
(
# 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
The script quite literally: - reads the first line and outputs it without a change - then while it reads the lines from file - we get the ip address as the 4 field from the line ( awk '{print $4}'
and similar would work too) - then we print the line with the output of the get_alias
function. 该脚本的字面意思是:-读取第一行并将其输出而不进行任何更改-然后在从文件读取行的同时-我们从该行的第4个字段中获取ip地址(
awk '{print $4}'
,类似的代码也可以工作)-然后我们使用get_alias
函数的输出来打印该行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.