将 Unix `cal` 输出转换为乳胶表代码:单行解决方案?
试图实现以下目标让我很挣扎:
使用简短而甜蜜的单行(或几行)将 Unix cal
输出转换为乳胶表代码。
例如:cal -h 02 2012 | $magicline 应该产生
Mo &Tu &We &Th &Fr \\
& & 1 & 2 & 3 \\
6 & 7 & 8 & 9 &10 \\
13 &14 &15 &16 &17 \\
20 &21 &22 &23 &24 \\
27 &28 & & & \\
到目前为止我能想到的唯一合理的解决方案是
cal -h | sed -r -e '1d' -e \
's/^(..)?(...)?(...)?(...)?(...)?(...)?(...)?$/\2\t\&\3\t\&\4\t\&\5\t\&\6\t\\\\/'
......而且我真的很努力。它的好处是不复杂且易于理解,坏处是“不灵活”(它无法应对一周 8 天的情况)并且有点冗长。我正在寻找可供学习的替代解决方案;-)
编辑:找到了另一种似乎可以接受的
cal -h | tail -n +2 |
perl -ne 'chomp;
$,="\t&";
$\="\t\\\\\n";
$line=$_;
print map {substr($line,$_*3,3)} (1..5)'
编辑:不错的解决方案:
cal -h | perl \
-F'(.{1,3})' -ane \
'BEGIN{$,="\t&";$\="\t\\\\\n"}
next if $.==1;
print @F[3,5,7,9,11]'
Trying to achieve the following struggled my mind:
Convert Unix cal
output to latex table code, using a short and sweet one-liner (or few-liner).
E.g cal -h 02 2012 | $magicline
should yield
Mo &Tu &We &Th &Fr \\
& & 1 & 2 & 3 \\
6 & 7 & 8 & 9 &10 \\
13 &14 &15 &16 &17 \\
20 &21 &22 &23 &24 \\
27 &28 & & & \\
The only reasonable solution I could come up with so far was
cal -h | sed -r -e '1d' -e \
's/^(..)?(...)?(...)?(...)?(...)?(...)?(...)?$/\2\t\&\3\t\&\4\t\&\5\t\&\6\t\\\\/'
... and I really tried hard. The nice thing about it being that it's uncomplicated and easy to understand, the bad thing about it that it's "unflexible" (It couldn't cope with a week of 8 days) and a little verbose. I'm looking for alternative solutions to learn from ;-)
EDIT: Found another one that seems acceptable
cal -h | tail -n +2 |
perl -ne 'chomp;
$,="\t&";
$\="\t\\\\\n";
$line=$_;
print map {substr($line,$_*3,3)} (1..5)'
EDIT: Nice one:
cal -h | perl \
-F'(.{1,3})' -ane \
'BEGIN{$,="\t&";$\="\t\\\\\n"}
next if $.==1;
print @F[3,5,7,9,11]'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 OS-X 上测试:
其中
cal
输出具有 3 个字符的列;可以更改{3}
以匹配您的cal
输出。Tested on OS-X:
Where
cal
output has 3-character columns;{3}
could be changed to match yourcal
output.使用 GNU 版本的
awk
:我使用英语
LANG
输出的cal
。命令:
输出:
awk
一行:结果:
Using the GNU version of
awk
:My output of
cal
using an englishLANG
.Command:
Output:
The
awk
one-line:Result:
我的新最爱:
my new favorite:
这可能对你有用:
This might work for you:
这适用于我的
cal
实现,它使用四个字符的列,并有一个显示月份和年份的初始标题行看起来好像你的可能有八个字符的列并且没有标题行,在哪种情况
应该可以解决问题,但要做好调整的准备。
This works for my implementation of
cal
, which uses four-character columns and has an initial title line showing the month and yearIt looks as though yours may have eight-character columns and has no title line, in which case
should do the trick, but be prepared to tweak it.
这将产生:
您可以轻松地将
\t
替换为您想要的空格数This will produce:
You can easily replace
\t
with number of spaces you wish