将每个x(动态)行数移动到一行[Shell]

时间:2016-12-01 18:15:11

标签: linux excel shell awk

所以我的数据看起来像这样

/blah
    etc1: etc
    etc2
    etc3: etc
    etc4
/blah
    etc1: etc
    etc2
    etc3
/blah
    etc1: etc
    etc2
    etc3: etc
    etc4
/blah
    etc1
    etc2

所以我不能做一个特定数量的行,所以想到使用/作为分隔符并将每一行放到/同一行之后(逗号分隔?) 理想的预期产出:

/blah,etc1: etc,etc2,etc3: etc,etc4,,
/blah,etc1,etc2,etc3,,
/blah,etc1: etc,etc2,etc3: etc,etc4,,
/blah,etc1,etc2,,

首选shell / bash / ksh,但excel解决方案也可以。

2 个答案:

答案 0 :(得分:0)

这是一个awk解决方案:

awk ' 
  /^\// { if (NR > 1) print ","; printf "%s,", $0; next } 
  { gsub(/^ +| +$/, ""); printf "%s,", $0 } 
  END { print "," }
' file

请注意,它假设输入文件以类似于/blah的行开头,但不以一行结束。

塞进一个(不太可读的)单行:

awk '/^\// {if(NR>1) print","; printf"%s,",$0; next} {gsub(/^ +| +$/, ""); printf"%s,",$0} END {print","}' file

答案 1 :(得分:0)

sed解决方案

sed -r ':a;N;$!ba;s/\n\s+/,/g' input | sed 's/$/,,/'

你明白了,

/blah,etc1: etc,etc2,etc3: etc,etc4,,
/blah,etc1: etc,etc2,etc3,,
/blah,etc1: etc,etc2,etc3: etc,etc4,,
/blah,etc1,etc2,,