1

我需要更改 HTML 文件的价格,该文件搜索并将它们存储在数组中,但我必须更改并保存 /nuevo-focus.html

price=( `cat /home/delkav/info-sitioweb/html/productos/autos/nuevo-focus.html | grep -oiE '([$][0-9.]{1,7})'|tr '\n' ' '` )

 price2=( $90.880 $0 $920 $925 $930 $910 $800 $712 $27.220 $962 )
 sub (){
 for item in "${price[@]}"; do
    for x in ${price2[@]}; do
      sed s/$item/$x/g > /home/delkav/info-sitioweb/html/productos/autos/nuevo-focus.html
     done
 done
 }

 sub

输出 "cat /home/.../nuevo-focus.html|grep -oiE '([$][0-9.]{1,7})'|tr '\n' ' '` )" 是...

$86.880 $0 $912 $908 $902 $897 $882 $812 $25.725 $715
4

1 回答 1

5

bash变量中$0,通过$9引用正在运行的脚本的相应命令行参数。在行中:

price2=( $90.880 $0 $920 $925 $930 $910 $800 $712 $27.220 $962 )

它们将扩展为空字符串或您为脚本提供的命令行参数。

尝试这样做:

price2=( '$90.880' '$0' '$920' '$925' '$930' '$910' '$800' '$712' '$27.220' '$962' )

编辑问题的第二部分

如果您尝试对该sed行执行的操作是替换文件中的价格,覆盖旧价格,那么您应该这样做:

sed -i  s/$item/$x/g /home/delkav/info-sitioweb/html/productos/autos/nuevo-focus.html

这将在原地 ( ) 执行替换-i,修改输入文件。


编辑问题的第三部分

我刚刚意识到您的嵌套循环并没有真正的意义。我假设您想要做的是用price相应的价格替换每个价格price2

如果是这种情况,那么您应该使用单个循环,遍历数组的索引:

for i in ${!price[*]}
do
    sed -i  "s/${price[$i]}/${price2[$i]}/g" /home/delkav/info-sitioweb/html/productos/autos/nuevo-focus.html
done

我现在无法测试它,但我认为它应该可以完成你想要的。

稍微解释一下:

${!price[*]}为您提供数组的所有索引(例如0 1 2 3 4 ...

然后,对于每个指数,我们将相应的旧价格替换为新价格。不需要像您所做的那样使用嵌套循环。当你执行它时,你基本上在做的是:

replace every occurence of "foo" with "bar"
# at this point, there are now no more occurences of "foo" in your file
# so all of the other replacements do nothing
replace every occurence of "foo" with "baz"
replace every occurence of "foo" with "spam"
replace every occurence of "foo" with "eggs"
replace every occurence of "foo" with "qux"
replace every occurence of "foo" with "whatever"
etc...
于 2012-08-01T02:59:47.023 回答