【问题标题】:Set Counter Value设置计数器值
【发布时间】:2021-11-18 12:53:43
【问题描述】:

你好编程专业, 我想在脚本的第二个回显中获得总的计数器值,但计数器在 do 函数中运行。 有没有办法让它在 do 函数之前写入值。 或者如果我在计数器下写前 2 个回显行,我得到了值,但我需要在 xml 文件的顶部写下这一行! 有没有办法做到这一点,也许从 middel 脚本的计数器值到总和最后在 echo 第二行。

#XML headers
echo '<?xml version="1.0" encoding="utf-8"?>' > $tmp_gigabook
echo "<list response=\"get_list\" type=\"pr\" reqid=\"1000\" total=\"$counter\" first=\"1\" last=\"$counter\">" >> $tmp_gigabook
declare counter=1000
# Read intermediate csv-xml-ish into array of lines
readarray -t lines < $tmp_intermediate
# Walk through lines and output entries
for line in "${lines[@]}"
do
    # Split line into columns
    # Fix v 0.3 Parentheses bug: explicitly set IFS, don't rely on defaults
    IFS=$'\t'
    read -a columns <<< "$line"
    # Output xml

((counter++))

    echo "<entry id=\"$counter\">
    <ln>${columns[0]}</ln> 
    <fn>${columns[1]}</fn>
    <mb>${columns[2]}</mb>
    <hm>${columns[3]}</hm>
     </entry>" >> $tmp_gigabook

done
# XML footer
echo '</list>' >> $tmp_gigabook
# Remove placeholders / markers
sed -i 's/±//g' $tmp_gigabook

## Finalise
# Copy and adjust
cp -f $tmp_gigabook $instance/$phonebook
chown phonesystem:phonesystem $instance/$phonebook
chmod 600 $instance/$phonebook

【问题讨论】:

    标签: xml bash csv echo counter


    【解决方案1】:

    您可以推迟打印您的标题,直到您处理完文件并使用cat 将其与文件内容一起打印回文件中:

    # remove echo statements for the header, create the blank file first
    echo -n >"$tmp_gigabook" # or :>"$tmp_gigabook"
    
    # snip - declare / readarray here
    
    for line in "${lines[@]}"
    do
       # snip - write to file as usual
    done
    # XML footer
    echo '</list>' >> "$tmp_gigabook"
    
    # rewrite the file but prepend the header information w/counter values
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <list response=\"get_list\" type=\"pr\" reqid=\"1000\" total=\"$counter\" first=\"1\" last=\"$((counter-1000))\">
    $(cat "$tmp_gigabook")" > "$tmp_gigabook"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      相关资源
      最近更新 更多