Bash:重复执行命令并将输出选项卡分隔到文件

时间:2016-09-21 10:44:31

标签: bash while-loop append multiple-columns do-while

我想让我的文件像这样记录:

while [ "true" ]
do 
echo "Time_Namelookup:" >> $file
curl -w "%{time_namelookup}\t" -o /dev/null -s https://website.com/
echo "Time_connect" >> $file
curl -w "%{time_connect}\t" -o /dev/null -s https://website.com/
echo "Time_Starttransfer:" >> $file
curl -w "%{time_starttransfer}\t" -o /dev/null -s https://website.com/
sleep 5
done

我希望每n秒将值添加到特定行。

我得到了这样的代码:

Time_Namelookup: 0,1         
Time_Connect: 0,34         
Time_Starttransfer: 0,9   

Time_Namelookup:  0,2      
Time_Connect:0,23  0,23        
Time_Starttransfer:  0,23   

Time_Namelookup:  0,45       
Time_Connect:  0,11         
Time_Starttransfer: 0,12 

但我有点像

animal

你能帮助我吗?

2 个答案:

答案 0 :(得分:0)

你可以把它放在你的循环中

if [ ! -f $file ]; then
  echo "Time_Namelookup:" > $file
  echo "Time_Connect:" >> $file
  echo "Time_Starttransfer:" >> $file
fi

name_lookup=$(curl -w "%{time_namelookup}\t" -o /dev/null -s https://website.com/)
connect=$(curl -w "%{time_connect}\t" -o /dev/null -s https://website.com/)
starttransfer=$(curl -w "%{time_starttransfer}\t" -o /dev/null -s https://website.com/)
sed -i -e "s/\(Time_Starttransfer:.*\)/\1 $starttransfer/" \
  -e "s/\(Time_Connect:.*\)/\1 $connect/" \
  -e "s/\(Time_Starttransfer:.*\)/\1 $starttransfer/" \
  $file

答案 1 :(得分:0)

你可以试试这个;

file=yourFile
echo "Time_Namelookup   :" >> $file
echo "Time_Connect      :" >> $file
echo "Time_Starttransfer:" >> $file
while [ "true" ]
do 
time_namelookup=$(curl -w "%{time_namelookup}\t" -o /dev/null -s https://website.com/)
time_connect=$(curl -w "%{time_connect}\t" -o /dev/null -s https://website.com/)
time_starttransfer=$(curl -w "%{time_starttransfer}\t" -o /dev/null -s https://website.com/)
sed -i "/Time_Namelookup   :/s/$/\t$time_namelookup/" $file
sed -i "/Time_Connect      :/s/$/\t$time_connect/" $file
sed -i "/Time_Starttransfer:/s/$/\t$time_starttransfer/" $file
sleep 5
done

sed -i :即可进行就地编辑。

以下部分是在文件中找到“Time_Namelookup:”。

/Time_Namelookup   :/  

/秒/ $ / \ T $ time_namelookup /“

s         :substitute command
/../../   :delimiter
$         :end of line character.
\t$time_namelookup: to append tab and the value.