我有一个这样的文件 -
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
如何将其与其他列结合使用?
答案 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 ||
您的尝试几乎就在那里,您应该查看printf
和split
函数。
答案 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