使用awk重新格式化CSV文件

时间:2013-03-01 08:59:42

标签: shell sed awk

我有一个这样的文件 -

 1,[test1] Joe,OK
 2,[test2] Jack,OK
 3,[test3] Tom,FAIL

我正在打印这样的文件 -

cat file | awk -F"," '{ print "||"  $1 "||" $2 "||" $3 "||" }' 

我希望输出文件像这样 -

|| 1 || Joe  || OK ||
|| 2 || Jack || OK ||
|| 3 || Tom  || FAIL ||

即。 [test1] Joe已修改为Joe我们如何在每列上执行此类操作。

echo "[test1] Joe" | sed 's/\[.*\]\s//g'

只给我Joe如何将其与其他列结合使用?

4 个答案:

答案 0 :(得分:3)

awk中,正确间距:

$ awk -F, '{split($2,a," ");printf "||%s || %-4s || %s ||\n",$1,a[2],$3}' file
|| 1 || Joe  || OK ||
|| 2 || Jack || OK ||
|| 3 || Tom  || FAIL ||

您的尝试几乎就在那里,您应该查看printfsplit函数。

答案 1 :(得分:2)

使用sed:

   sed 's/\[[^]]*\]//;s/^/|| /;s/$/ ||/;s/,/ || /g' input

<强>输出

|| 1 ||  Joe || OK ||
|| 2 ||  Jack || OK ||
|| 3 ||  Tom || FAIL ||

使用sed -i

进行就地开始

答案 2 :(得分:0)

一种方式:

awk -F, '{$1=OFS""$1;$NF=$NF""OFS;sub(/.* /,"",$2);}1' OFS=" || " file

运行上述内容:

 ||  1 || Joe || OK ||
 ||  2 || Jack || OK ||
 ||  3 || Tom || FAIL ||

答案 3 :(得分:0)

awk -F"," '{gsub(/,\[.*?\]|,|^|$/," || ",$0) }1' your_file

perl -plne 's/^|,/ || /g;s/\[.*?\]//g' your_file

测试如下:

> cat temp
1,[test1] Joe,OK
2,[test2] Jack,OK
3,[test3] Tom,FAIL
> perl -plne 's/^|,|$/ || /g;s/\[.*?\]//g' temp
 || 1 ||  Joe || OK || 
 || 2 ||  Jack || OK || 
 || 3 ||  Tom || FAIL ||
> awk -F"," '{gsub(/,\[.*?\]|,|^|$/," || ",$0) }1' temp
 || 1 ||  Joe || OK || 
 || 2 ||  Jack || OK || 
 || 3 ||  Tom || FAIL || 
> 

如果要替换文件inplace use:

perl -i -plne 's/^|,|$/ || /g;s/\[.*?\]//g' your_file