变量覆盖带有"echo"字样的文本问题.在巴什 [英] Variables overwriting text problem with "echo" in Bash
问题描述
我使用OS X 10.6.5,Bash.
I use OS X 10.6.5, Bash.
运行此命令时:
echo $IP; echo of; echo $IPLINES
我得到以下输出:
219.80.4.150:3128
of
1108
运行此命令时:
echo $IP of $IPLINES
我得到以下输出:
of 1108.150:3128
我希望得到:
219.80.4.150:3128 of 1108
什么会导致我得到的输出失真?
What would cause the distorted output I am getting?
实际的脚本是这样的:
#!/bin/bash
IPLINES=`cat a.txt | wc -l | awk '{print $1}'`
if [ $IPLINES > 1 ]; then
LINE=`expr $RANDOM % $IPLINES + 1`
IP=`head -$LINE a.txt | tail -1`
sed -e "${LINE}d" -i .b a.txt
echo $IP of $IPLINES
fi
推荐答案
在这里有一个疯狂的猜测:您正在从.txt文件中提取IP变量-如果是Windows文件或编码为Windows样式,则行尾用\r\n
.您删除了换行符,但是如果其中包含\r
会导致您回到该行的开头怎么办?
A wild guess here: you are extracting the IP variable from a .txt file -- if that's a Windows file, or is encoded Windows-style, lines end with \r\n
. You take the newline away, but what if there's a \r
in it that's making you go back to the beginning of the line?
快速进行脏修复,不问任何问题:使用echo -n
,它将在回显文本的末尾替换换行符.
Quick dirty fix with no questions asked: use echo -n
, it supresses the newline at the end of the echoed text.
echo -n $IP; echo -n of; echo -n $IPLINES
如果问题仍然存在,那可能就是我上面所说的.尝试右修剪$IP
.
If the problem persists, it's probably what I said above. Try right-trimming $IP
.
对不起,没有看到OSX部分.在OSX中,行以\r
结尾–一定是问题所在.
didn't see the OSX part, sorry. In OSX, lines end with \r
-- that must be the issue.
这篇关于变量覆盖带有"echo"字样的文本问题.在巴什的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!