2010-07-19 60 views
1

我有以下shell脚本:获取参数

#! /bin/sh 

while read page_section 
    page=${page_section%%\ *} 
    section=${page_section#* }  #NOTE: `%* }` is NOT a comment 

    wget --quiet --no-proxy www.cs.sun.ac.za/hons/$page -O html.tmp & wait 

# echo ${page_section%%\ *} # verify correct string chopping 
# echo ${page_section#* } # verify correct string chopping 

    ./DokuWikiHtml2Latex.py html.tmp $section & wait 
done < inputfile 

和输入文件是这样的:

doku.php?id=ndewet:tools:tramonitor TraMonitor 
doku.php?id=ndewet:description Implementation -1 
doku.php?id=ndewet:description Research\ Areas -1 

脚本下载一个在inputfile中分配的网页数量,然后必须将其余行(例如“Implementation -1”或“Research \ Areas -1”)传递给python脚本。

现在的粘性位。当此示例文件的第三行处理它通过“研究\区”的python脚本作为两个单独的参数,以证实:

>>> print sys.argv 
['./DokuWikiHtml2Latex.py', 'html.tmp', 'Research', 'Areas', '-1'] 

我怎样才能得到多字节,像“研究领域“从输入文件到Python脚本的单个参数?我试过逃避'\',也做

./DokuWikiHtml2Latex.py html.tmp `echo ${section#* }` 

除其他事情,但无济于事。

输入行末尾的数字是另一个参数,但是是可选的。

回答

1

就让read做解析的东西:

while read page section rest 
do 
    echo "Page: $page" 
    echo "Section: $section" 
done < inputfile 

对于优雅的处理可选参数,使用数组:

while read -a fields 
do 
    wget --quiet --no-proxy "www.cs.sun.ac.za/hons/${fields[0]}" -O html.tmp 
    unset "fields[0]" 
    ./DokuWikiHtml2Latex.py html.tmp "${fields[@]}" 
done < inputfile 

务必注明您的变量!

+0

你应该把各地的数组元素的报价,你没有设置到防止文件通配:'未设置“字段[0]”'(如果有文件名为“fields0”)。演示:'test =(1 2 3); touch test0;未设置测试[0]; declare -p test;未设置“测试[0]”;申报-p测试' – 2010-07-19 17:40:55

+0

@丹尼斯威廉姆森:谢谢。 – Philipp 2010-07-19 18:02:30

+0

不客气。我忘了证明一个名为'test0'的变量,如果它存在的话,将会因为文件的通配符和存在而被取消设置:'test =(1 2 3); TEST0 = 4; touch test0;未设置测试[0];回声“test0 = $ test0”; declare -p test;未设置“测试[0]”;声明-p测试“ – 2010-07-19 18:24:53

0

通常多字的参数可以作为一个传递用引号,所以:约$部分

doku.php?id=ndewet:description "Research Areas" -1 
2

把双引号:

./DokuWikiHtml2Latex.py html.tmp "$section" & wait