【发布时间】:2017-08-29 02:11:07
【问题描述】:
我想将包含 testfile.ps 的所有其他内容的数组值插入到 result.ps 文件中,但数组值没有打印出来,请帮忙。 我的要求是每次满足条件时数组下一个索引值应该与 testfile.ps 的其他内容一起打印到 result.ps 中
实际上 arr[0] 和 arr[1] 在我的项目中是大字符串,但为简单起见,我正在编辑它
#!/bin/bash
a[0]=""lineto""\n""stroke""
a[1]=""476.00"" ""26.00""
awk '{ if($1 == "(Page" ){for (i=0; i<2; i++){print $arr[i]; print $0; }}
else print }' testfile.ps > result.ps
测试文件.ps
(Page 1 of 2 )
move
(Page 1 of 3 )
"gsave""\n""2.00"" ""setlinewidth""\n"
result.ps 应该是
(Page 1 of 2 )
lineto
stroke
move
(Page 1 of 3 )
476.00 26.00
gsave
2.00
setlinewidth
表示一旦满足第二次条件,数组索引应该递增到 1,它应该打印 a[1]
我也应用了这个方法,只有单个数组元素但没有得到任何输出
awk -v "a0=$a[0]" 'BEGIN {a[0]=""lineto""stroke""; if($1 == "move" ){for (i in a){ print a0;print $0; }} else print }' testfile.txt
编辑: 嗨,我已经在一定程度上解决了这个问题,但卡在一个地方,我如何比较两个字符串,如 "a=476.00 1.00 lineto\nstroke\ngrestore\n" 和 "b=26.00 moveto\n368.00 1.00 lineto\ n" 在 awk 命令中,我正在尝试
awk -v "a=476.00 1.00 lineto\nstroke\ngrestore\n" -v "b=26.00 moveto\n368.00 1.00 lineto\n" -v "i=$a" '{
if ($1 == "(Page" && ($2%2==0 || $2==1) && $3 == "of"){
print i;
if [ i == a ];then
i=b; print $0;
fi
else if [ i == b ];then
i=c; print $0;
fi
else print $0;
}'testfile.txt
【问题讨论】:
-
awk 不是 shell,它是一个完全不同的工具,有自己的语法、变量等。你不能在 awk 中使用 shell 变量,就像在 C 或 Java 中使用 shell 变量一样。 edit您的问题包括简洁、可测试的样本输入和预期输出,以便我们为您提供帮助。
-
即使 shell 和 awk 使用相同的变量,它们也必须拼写相同,即
a[0] !- $arr[0];-) 。祝你好运。 -
您对
$arr[i]有什么期望?您是否尝试引用上面定义的 shell 数组a?它甚至不是同名,而且你不能(轻松)在 awk 中获取 shell 变量... -
@EdMorton:感谢您的评论,为了更清楚,我已经编辑了问题
-
@dawg:感谢您的评论,为了更清楚,我已经编辑了这个问题
标签: bash shell awk sed string-comparison