我正在尝试在每一行中使用awk将当前日期字段追加到我的管道分隔内容中。而不是预期的,整个16列被附加到第17(新)位置。我试过改变一些事情,但没有帮助。我认为有一些基本的错误。我可以在这里得到帮助吗?
awk ' BEGIN{FS="|";}
{
$17=$(date +"%d-%m-%Y");
printf("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
$11, $12, $13, $14, $15, $16, $17);
}' /Users/temp/dispn/content3.txt | less > /Users/temp/dispn/content4.txt
输入(16个字段):
EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0
我的输出
EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0|EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0
预期(17个领域):
EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0|06-22-2014
答案 0 :(得分:2)
我想这里的问题是脚本中的$(date +"%d-%m-%Y");
被解释为$0
因为bash
没有扩展它。为了防止这种情况,您可以使用双引号定义awk
脚本,如下所示:
awk "{print \$0\"|\"$(date +\"%d-%m-%Y\")}"
需要所有类型的转义$
和"
字符才能使其正常工作。
如果您不需要使用awk
,但也可以使用sed
,则可以使用:
sed "s/$/|$(date +"%d-%m-%Y")/"
答案 1 :(得分:2)
将日期指定给变量并使用整行打印
awk -F'|' -v var=$(date +"%d-%m-%Y") '{print $0,var}' OFS="|"
示例:强>
$ echo 'EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0' | awk -F'|' -v var=$(date +"%d-%m-%Y") '{print $0,var}' OFS="|"
EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0|22-06-2014
如果您想要month-date-year
格式,请将date
命令更改为date +"%m-%d-%Y"