5

我有一个包含大约 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' ','
4

4 回答 4

6

只需使用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
于 2012-07-05T08:15:31.587 回答
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
于 2012-07-05T08:26:00.227 回答
0

一种使用方式sed

Igor Chubin 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
于 2012-07-05T08:28:22.257 回答
0

在 sed 的命令中使用标志s将每 20 个逗号替换为换行符:

 < filelist.txt tr '\n' , | sed ':a; s/,/\n/20; P; D; ta'; echo
于 2012-07-05T14:01:27.407 回答