2012-07-05 76 views
4

我有大約150到200文件名翻譯換行符,逗號

abc.txt 
pqr.txt 
xyz.txt 
... 
... 

我需要逗號的字符串分隔的文件列表的文本文件。 每個字符串應該不超過20個文件。所以回聲看起來像這樣...

$string1="abc.txt,pqr.txt,xyz.txt..." 
$string2="abc1.txt,pqr1.txt,xyz1.txt..." 
... 

字符串的數量將根據文件中的行數而不同。我寫了這樣的事情......

#!/bin/sh 
delim=',' 
for gsfile in `cat filelist.txt` 
do 
filelist=$filelist$delim$gsfile 
echo $filelist 
done 

翻譯命令工作正常,但我要如何限制每串20名?

cat filelist.txt | tr '\n' ',' 
+0

你可以有一個變量數組和循環槽列表檢查%20 == 0,然後將分配給來自變量數組的下一個變量 – ant

回答

5

只需使用xargs

$ seq 1 50 | xargs -n20 | tr ' ' , 
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 
41,42,43,44,45,46,47,48,49,50 
0

這可能會爲你工作:

seq 41 | paste -sd ',,,,,,,,,,,,,,,,,,,\n' 
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 
41 

或GNU sed的:

seq 41 | sed ':a;$bb;N;s/\n/&/19;Ta;:b;y/\n/,/' 
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 
41 
0

一個使用sed方式:

添加像伊戈爾出殯 50號至infile

內容的
seq 1 50 >infile 

script.sed

:b 
## While not last line... 
$! { 
    ## Check if line has 19 newlines. Try substituting the line with itself and 
    ## check if it succeed, then append next line and do it again in a loop. 
    s/\(\n[^n]*\)\{19\}/&/ 
    ta 
    N 
    bb 
} 

## There are 20 lines in the buffer or found end of file, so substitute all '\n' 
## with commas and print. 
:a 
s/\n/,/g 
p 

運行它想:

sed -nf script.sed infile 

有了以下的輸出:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 
41,42,43,44,45,46,47,48,49,50 
0

使用標誌在sed的s命令以換行符替換每20逗號:

< filelist.txt tr '\n' , | sed ':a; s/,/\n/20; P; D; ta'; echo