这个脚本的输出为什么丢内容?

sh/bash/dash/ksh/zsh等Shell脚本
回复
sainry
帖子: 26
注册时间: 2007-07-19 13:28

这个脚本的输出为什么丢内容?

#1

帖子 sainry » 2010-10-01 20:53

#!/bin/bash

#获取时间:
#date | cut -d ' ' -f5 | cut -d : -f1

wget -O /tmp/tianqi http://www.weather.com.cn/html/weather/101091001.shtml
cd /tmp
DU=$(head -226 ./tianqi | tail -1 | cut -d '>' -f4 | cut -d '<' -f1)

#day1
DAY_1_DATE=$(head -216 ./tianqi | tail -1 | cut -d '>' -f2 | cut -d '<' -f1) #日期
DAY_1_TIME=$(head -217 ./tianqi | tail -1 | cut -d '>' -f2 | cut -d '<' -f1) #夜间、白天
DAY_1_TMP=$(head -223 ./tianqi | tail -1 | cut -d '>' -f3 | cut -d '<' -f1) #天气
DAY_1_LOW=$(head -226 ./tianqi | tail -1 | cut -d '>' -f3 | cut -d '<' -f1) #低温
DAY_1_WIND=$(head -231 /tmp/tianqi | tail -1) #风向
DAY_1_LEVEL=$(head -236 /tmp/tianqi | tail -1) #风力

echo $DAY_1_DATE
echo $DAY_1_TIME $DAY_1_TMP
echo "温度: "$DAY_1_LOW$DU
echo $DAY_1_WIND $DAY_1_LEVEL


新手,拜托各位老大给看看
tusooa
帖子: 6548
注册时间: 2008-10-31 22:12
系统: 践兔
联系:

Re: 这个脚本的输出为什么丢内容?

#2

帖子 tusooa » 2010-10-01 22:58

搜索 5行 天气脚本。

代码: 全选

] ls -ld //
头像
astolia
论坛版主
帖子: 6444
注册时间: 2008-09-18 13:11

Re: 这个脚本的输出为什么丢内容?

#3

帖子 astolia » 2010-10-01 23:33

鄙视楼上。

你所谓的丢内容是指风向没输出吧
head -231 /tmp/tianqi | tail -1 取得的风向后面还带有一个换行一个回车,你可以通过 head -231 /tmp/tianqi | tail -1 | od -x 来看到。
而回车符在终端下的作用是将光标位置移动到行首,所以 echo $DAY_1_WIND $DAY_1_LEVEL 这句先输出了风向后,再输出的风力时就把已经输出的风向给覆盖掉了。

简单的一段脚本程序来演示回车和换行以及两者混合后的输出效果。

代码: 全选

printf "#1 this is the first line.\nsecond line?\n"
printf "#2 this is the first line.\rsecond line?\n"
printf "#3 this is the first line.\r\nsecond line?\n"
printf "#4 this is the first line.\n\rsecond line?\n"
解决办法就是去除回车符

代码: 全选

DAY_1_WIND=$(head -231 /tmp/tianqi | tail -1 | sed 's/\r//g') #风向
另外,你这个程序没必要输出到临时文件,wget可以直接输出到标准输出

代码: 全选

page=$(wget http://www.weather.com.cn/html/weather/101091001.shtml -O-)
输出第n行也不必head+tail,用sed吧

代码: 全选

sed -n '2p'
就输出第2行了
sainry
帖子: 26
注册时间: 2007-07-19 13:28

Re: 这个脚本的输出为什么丢内容?

#4

帖子 sainry » 2010-10-02 22:23

谢谢您,astolia
谢谢!
tusooa
帖子: 6548
注册时间: 2008-10-31 22:12
系统: 践兔
联系:

Re: 这个脚本的输出为什么丢内容?

#5

帖子 tusooa » 2010-10-06 17:24

astolia, 不建议用\r。用\e[1G。
更清楚点。

代码: 全选

] ls -ld //
回复