尝试在 EOF heredoc 中使用大括号扩展

Trying to use brace expansion in EOF heredoc

我正在尝试在 EOF heredoc 中使用大括号扩展。这样做很麻烦。我正在尝试创建一个脚本来告诉人们他们的生肖,它基于 year/month/day 示例:1984 年 2 月 2 日 - 1985 年 2 月 19 日 = RAT

awk -v year="" '
[=10=] ~ year {
    print 
    found = 1
    exit
}
END {
    if (!found)
        exit 1
}
' <<EOF
Rat 1984 1985 1996 2008 2020 2034
Ox  1985 1997 2009 2021
Tiger 1986 1998 2010 2022
Rabbit 1987 1999 2011 2023
Dragon 1988 2000 2012 2024
Snake 1989 2001 2013 2025
Horse 1990 2002 2014 2026
Goat 1991 2003 2015 2027
Monkey 1992 2004 2016 2028
Rooster 1993 2005 2017 2029
Dog 1994 2006 2018 2030
Pig 1995 2007 2019 2031
EOF

我想使用 Rat 1984{02..12}{0..31} 1985{01,02}{0..31} 来扩展我的 awk 以搜索提供的数字范围在大括号中。这可能吗? 谢谢

here documents 上的 Bash 手册说:

If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.

您样本中的 是未加引号的 EOF

扩展列表不包括brace expansion;我觉得你运气不好。


Is there a workaround?

它可能部分取决于您的 Bash 版本 — 在 macOS Sierra 10.12.4 上,默认值为 3.2.57,其输出与 Bash 4.3 不同。

大括号扩展在某种程度上是一个有限的事情——有很多事情你不能用它来做,因为变量只有在大括号扩展发生之后才会被扩展。

这可能是一个提示;不过,我不太确定您如何将它包含在脚本中。

$ printf 'Rat %s\n' 1984{02..12}{0..31} 1985{01,02}{0..31}
Rat 198420
Rat 198421
Rat 198422
Rat 198423
Rat 198424
…
Rat 19850227
Rat 19850228
Rat 19850229
Rat 19850230
Rat 19850231
$ bash-4.3 -c "printf 'Rat %s\n' 1984{02..12}{0..31} 1985{01,02}{0..31}"
Rat 1984020
Rat 1984021
Rat 1984022
Rat 1984023
Rat 1984024
Rat 1984025
…
Rat 19850226
Rat 19850227
Rat 19850228
Rat 19850229
Rat 19850230
Rat 19850231
$

请注意,前导零在 198420 中消失,以此类推 Bash 3.x。我对第 0 天很好奇,更不用说 2 月 31 日了,但我想这些都会得到处理。

现在您必须决定如何将其合并到您的脚本中以生成数据。您可能会发现生成脚本然后运行生成的脚本的脚本比直接编写脚本更易于管理。