2016-11-14 102 views
0

我有一個名爲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); 

回答

1

嘗試從這個簡單的代碼開始。隨意修改:

cat p.txt | while read a; 
do 
    read b; 
    read c; 
    echo $a $b $c; 
done 

變量a,b,c有3個值。

+0

它工作的很好,但它完全可以被3整除。但如果它不是它給我(201601 ,,)這是失敗的。 –

+1

您想要按3組進行處理。如果最後一組中只有2個或1個項目,則按您想要的方式進行處理。您可以使用例如「如果」聲明。 – quantummind

2

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行輸出存儲到變量或數組。

0

爲了記錄,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

相關問題