将换行符翻译为逗号

时间:2012-07-05 08:05:40

标签: shell sed awk grep

我有一个文本文件,其中包含大约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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

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

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