【问题标题】:Translate newline to comma将换行符翻译成逗号
【发布时间】:2012-07-05 14:45:04
【问题描述】:

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

【问题讨论】:

  • 你可以有一个变量数组,并通过你的列表循环检查 % 20 == 0,然后从你的变量数组中分配给下一个变量

标签: shell sed awk grep


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这可能对你有用:

    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
    

    【讨论】:

      【解决方案3】:

      一种使用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
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-11-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-06
          • 2012-10-13
          • 2020-05-29
          相关资源
          最近更新 更多