从批处理文件中读取一定长度的文件
问题描述:
我有一个名为p.txt的文件。 它包含以下值:从批处理文件中读取一定长度的文件
201601
201602
201603
201604
201605
201606
201607
201608
201609
201610
我想在一批3.即阅读本记录 一个变量将有以下三个值
201601
201602
201603
在第一次迭代。在第二次迭代中它将具有接下来的三行
201604
201605
201606
如果数字没有完全除以3,则迭代将被除数+1。
unix中怎么可能?
我迄今为止尝试:
PERD=`cat P.txt`
for perd in `cat PERD_ID.txt`;
do
bteq << EOF
.logon ${conn_string};
/* Database*/
DATABASE $ET;
/* Update NULL LOCL_SEGMNT3_IDNs*/
INSERT INTO T
SELECT *
FROM A
WHERE PERIOD IN ($PERD);
.if errorcode != 0 then .exit 5.1;
.LOGOFF
.EXIT
EOF
done
当前代码读取每一行和DB执行插入。为了获得更好的性能,我希望将这些查询用于3个时期。
/* Update NULL LOCL_SEGMNT3_IDNs*/
INSERT INTO T
SELECT *
FROM A
WHERE PERIOD IN (201601,201602,201603);
答
尝试从这个简单的代码开始。随意修改:
cat p.txt | while read a;
do
read b;
read c;
echo $a $b $c;
done
变量a,b,c有3个值。
答
bash
没有任何简单的工具/例程一次读取n
行。这样的xargs
与读取使用选项(-L
)3线和使用while循环过read
命令,像的组合:
# 'count' a local counter variable, incremented in while-loop
# 'file' is sample input file
$ count=1; xargs -L 3 <file | while read line; do printf "Iteration-->%d\n%s\n" "$((count++))" "${line// /$'\n'}"; done
它产生一个输出作为
Iteration-->1
201601
201602
201603
Iteration-->2
201604
201605
201606
Iteration-->3
201607
201608
201609
Iteration-->4
201610
,可以优化我的解决方案将每3行输出存储到变量或数组。
答
为了记录,mapfile/readarray bash方法可以适用。
例子:
mapfile -n3 varA<file;echo ${varA[@]} # Get the first three lines from file and store them in a array called varA.
mapfile -s3 -n3 varB<file;echo ${varB[@]} # Skip 3 - get next three lines and store it in another array varB
mapfile -s6 -n3 varC<file;echo ${varC[@]} # Skip 6 - get next three lines, and store it in another array varC
意思就是通过操纵-s选项,你可以达到你所需要的。
也请记住下面的命令:
mapfile var<file # This fills an array called var with all the lines of file. var[0] is the first line, var[1] is the second line, etc
echo ${var[@]} # Prints the whole array
echo ${var[2]} # Prints a particular array item
echo ${#var[@]} #Prints the number of elements in array = number of lines read
阵列在bash从零开始计数。 可以强制映射文件通过从1开始通过使用-O1选项映射的数组:
mapfile -O1 var<file
PS:其实-O1第一阵列值/第一文件线分配给这两个变种[0]和变种[ 1]职位。因此,您将能够将数组的第1-2-3行指向var [1] -var [2] -var [3]而不是默认的var [0] --var [1] --var [2]
GV
它工作的很好,但它完全可以被3整除。但如果它不是它给我(201601 ,,)这是失败的。 –
您想要按3组进行处理。如果最后一组中只有2个或1个项目,则按您想要的方式进行处理。您可以使用例如“如果”声明。 – quantummind