【发布时间】:2021-10-03 05:25:52
【问题描述】:
我正在从一位同事那里接过一个 bash 脚本,该脚本读取一个文件,处理它并根据 while 循环中的行打印另一个文件。
我现在需要为其添加一些功能。我现在遇到的问题是读取文件并将每一行放入一个数组中,除了该行的第二列可以为空,例如:
对于以\t 为分隔符的文本文件:
A\tB\tC
A\t\tC
对于相同但以, 作为分隔符的 CSV 文件:
A,B,C
A,,C
然后应该给
["A","B","C"] or ["A", "", "C"]
我接手的代码如下:
while IFS=$'\t\r' read -r -a col; do
# Process the array, put that into a file
lp -d $printer $file_to_print
done < $input_file
如果 B 被填充,这会起作用,但 B 现在有时需要为空,所以当输入文件保持为空时,创建的数组以及要打印的输出文件只是跳过这个空单元格(然后数组是 ["A","C"] )。
我尝试在 awk 上编写整个 bloc,但这带来了一系列问题,使得调用 lp 命令打印变得困难。
所以我的问题是,如何将行中的空单元格保存到我的 bash 数组中,以便我以后可以调用它并使用它?
非常感谢。我知道这可能很混乱,所以请询问,我会指定。
编辑:请求后,这是我尝试过的 awk 代码。这里的问题是它只打印最后一个打印请求,而我知道它会循环整个文件,并且 lp 命令仍在循环中。
awk 'BEGIN {
inputfile="'"${optfile}"'"
outputfile="'"${file_loc}"'"
printer="'"${printer}"'"
while (getline < inputfile){
print "'"${prefix}"'" > outputfile
split($0,ft,"'"${IFSseps}"'");
if (length(ft[2]) == 0){
print "CODEPAGE 1252\nTEXT 465,191,\"ROMAN.TTF\",180,7,7,\""ft[1]"\"" >> outputfile
size_changer = 0
} else {
print "CODEPAGE 1252\nTEXT 465,191,\"ROMAN.TTF\",180,7,7,\""ft[1]"_"ft[2]"\"" >> outputfile
size_changer = 1
}
if ( split($0,ft,"'"${IFSseps}"'") > 6)
maxcounter = 6;
else
maxcounter = split($0,ft,"'"${IFSseps}"'");
for (i = 3; i <= maxcounter; i++){
x=191-(i-2)*33
print "CODEPAGE 1252\nTEXT 465,"x",\"ROMAN.TTF\",180,7,7,\""ft[i]"\"" >> outputfile
}
print "PRINT ""'"${copies}"'"",1" >> outputfile
close(outputfile)
"'"`lp -d ${printer} ${file_loc}`"'"
}
close("'"${file_loc}"'");
}'
EDIT2:继续尝试寻找解决方案,我尝试了以下代码但没有成功。这很奇怪,因为只执行 printf 而不将其放入数组中就可以保持格式不变。
$ cat testinput | tr '\t' '>'
A>B>C
A>>C
# Should normally be empty on the second ouput line
$ while read line; do IFS=$'\t' read -ra col < <(printf "$line"); echo ${col[1]}; done < testinput
B
C
【问题讨论】:
-
根据您发布的信息,我们无法判断您为什么无法使用 Awk。也许更详细地解释它是如何不合适的,并向我们展示你做了什么;我猜这会比你当前的问题更容易解决。
-
谢谢,我加了awk代码。