bash回显问题
这是一个从 html 文件中提取一些数据的 bash 脚本。
price=`grep ' <td>\$' $1 | sed -e 's/<td>//g' -e 's:</td>::g' -e 's/\$ //g' -e 's/^ *//g'`
grep ' <td>\$' $1 | sed -e 's/<td>//g' -e 's:</td>::g' -e 's/\$ //g' -e 's/^ *//g'
echo "Price: $price"
sed 部分可能需要一些帮助,但这不是这里的问题。问题是,当我运行脚本时,它应该打印找到的值两次,对吗?但它只打印一次,第一次(没有“价格:”)。这里有什么问题?
Here's a bash script that extracts some data from a html file.
price=`grep ' <td>\
The sed part could use some help, but that's not the issue here. The problem is that, when I run the script, it should print the found value twice, right? But it prints it only once, the first time (Without the 'Price:'). What's the problem here?
$1 | sed -e 's/<td>//g' -e 's:</td>::g' -e 's/\$ //g' -e 's/^ *//g'`
grep ' <td>\
The sed part could use some help, but that's not the issue here. The problem is that, when I run the script, it should print the found value twice, right? But it prints it only once, the first time (Without the 'Price:'). What's the problem here?
$1 | sed -e 's/<td>//g' -e 's:</td>::g' -e 's/\$ //g' -e 's/^ *//g'
echo "Price: $price"
The sed part could use some help, but that's not the issue here. The problem is that, when I run the script, it should print the found value twice, right? But it prints it only once, the first time (Without the 'Price:'). What's the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是您返回的字符串中有一个
\r
,它在打印内容之前将光标返回到第一列。使用 od -c 进行验证。并使用适当的工具(例如xmlstarlet
来确保不会发生这种情况。The problem is that the string you're returning has a
\r
in it, which returns the cursor to the first column before printing stuff out. Useod -c
to verify. And use a proper tool such asxmlstarlet
to make sure this doesn't happen.第一个 grep 读取标准输入上的所有内容。然后,第二个 grep 阻止尝试从 stdin 读取。
The first grep reads everything on standard input. Then, the second grep blocks trying to read from stdin.
我猜测与显示的代码不同,分配实际上发生在子 shell 中,因此不可见(子 shell 退出时丢失),
恐怕您遇到了此处未显示的子 shell 问题。如果可以的话,发布更多您实际使用的代码。
- - 样本:
I'm guessing that unlike the code shown, the assignment actually happens in a subshell and therefore is not visible (lost on exit of subshell)
I'm afraid you ran into a subshell issue that you donot show here. Post more code that you actually use if you can.
--- Sample:
关于您使用 sed 的一些评论:
-e 's/^ *//g'
- 您不需要“g”:您的模式锚定在开头,因此它可以只匹配一次。不妨也寻找选项卡:-e 's/^[[:space:]]\{1,\}//'
-e 's// /g' -e 's:::g'
可以折叠为-e 's|||g'< /代码>
A couple of comments about your use of sed:
-e 's/^ *//g'
-- you don't need the "g": your pattern is anchored at the beginning so it can only match once. Might as well look for tabs too:-e 's/^[[:space:]]\{1,\}//'
-e 's/<td>//g' -e 's:</td>::g'
can be collapsed into-e 's|</\{0,1\}td>||g'