首页 > 解决方案 > Bash replacing part of output with a string

问题描述

I have this command that gets a certain output; command;

uptime | sed -e 's/^[ \t]*//' > temp                    
awk '{ sub(" min","") sub("users", "user");print > "temp" }' ./temp     

When I do cat temp, the output becomes;

13:24:16 up 1:33, 3 user, load average: 0.30, 0.56, 0.63

I want to replace 1:33 with this new time I created with this command;

awk '{printf("%02d:%02d\n",($1/60/60%24),($1/60%60))}' /proc/uptime > temp2

This gets as output;

01:33

So, in a nutshell, I want to replace 1:33 in the output of the first command with the output of the second command 01:33. I have been googling and trying but I keep failing so I decided to come here. I have found sollutions with sed, awk and grep. But I can't figure out the perfect one for this problem.

标签: linuxbash

解决方案


将字符串与正则表达式匹配并替换为sed.

echo '13:24:16 up 1:33, 3 user, load average: 0.30, 0.56, 0.63' | 
sed 's/up [^,]*,/up '"$(awk '{printf("%02d:%02d\n",($1/60/60%24),($1/60%60))}' /proc/uptime)"',/'

将输出(在我的系统上):

13:24:16 up 03:58, 3 user, load average: 0.30, 0.56, 0.63

推荐阅读