繁体   English   中英

如何替换变量中的脚本并在脚本中使用变量?

[英]How to replace script in variable and use variable in script?

我需要在此脚本中的变量中替换sed行,而在仅使用变量后。

cat postfix > "file.html" 
cal -h | sed '1{s|^|<table>\n<tr><th colspan="7">|;s|$|</th></tr>|};2,${s|\(..\) |<td>\1</td>|g;s|^|<tr>|;s|$|</tr>|};$s|$|\n</table>|' >> file.html
cat prefix >> "file.html"'

就像是

expression='1{s|^|<table>\n<tr><th colspan="7">|;s|$|</th></tr>|};2,${s|\(..\) |<td>\1</td>|g;s|^|<tr>|;s|$|</tr>|};$s|$|\n</table>|'

cat postfix > "file.html"
cal -h | sed "${expression}" >> file.html
cat prefix >> "file.html"

(并注意通常人们希望前缀在头部,而后缀在末尾……;但这正是基于其名称的期望)

尽管在这种情况下使用sed可以解决问题,但我认为是否需要维护此代码并不是一个好主意。

关于前置文件和后置文件的简短说明:通常,前缀是放在您的前面,而后缀是放在后面的东西。 反之亦然,这增加了混乱。

您想要的是将第一行作为标题,其余的拆分为表格单元格。

cal -h > tempfile
cat postfix > "file.html"
echo '<table>' >> "file.html"
echo '<tr><th colspan="7">' >> "file.html"
head -1 tempfile >> "file.html"
echo '</th></tr>' >> "file.html"
tail +1 | sed 's/^/<tr>;s/\(/<td>/g;s/\)/<\/td>/g;s/$/<\/tr>/' >> "file.html"
echo '</table>' >> "file.html"
rm tempfile

这已经使其更具可读性。

甚至更进一步:

first=yes
cat postfix > "file.html" #sic
echo '<table>' >> "file.html"
cal -h | while read line ; do
    if [ $first = yes ] ; then
        first=no
        echo "<tr><th colspan=\"7\">$line</th></tr>" >> "file.html"
    else
        tdopen=${line//\(/<td>}
        tdclose=${tdopen//\)/<\/td>}
        echo "<tr>$tdclose</tr>" >> "file.html"
    fi
done
echo '</table>' >> "file.html"
cat prefix >> "file.html" #sic

我认为,它比sed -clutter更具可读性。 但这只是我个人的偏爱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM