将换行符转换为逗号



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

只需使用 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

使用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
这可能

对你有用:

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

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

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

最新更新