虽然我在下面编写一些
awk
脚本,但它会生成许多不需要的 LF
。我想知道如何抑制(控制)此脚本中 LF
的输出。预先感谢您的好意建议。
awk '
BEGIN{
FS=OFS=","
}
{
nf=NF
s=0 # initialization
if($1==3){print "1,"; s+=50}else{print "0,"}
if($2==1){print "1,"; s+=50}else{print "0,"}
print s
print ","
}END{}' file
文件(文件)的内容类似于,
3,1
3,2
在这种情况下,输出就像
1,
1,
100
,
1,
0,
50
,
这非常笨拙。我想要的输出是这样的,
1,1,100
1,0,50
$ cat input
3,1
3,2
$ awk 'BEGIN{FS=OFS=","}{c1=c2=sum=0;}$1==3{c1=1;sum+=50}$2==1{c2=1;sum+=50}{print c1,c2,sum}' input
1,1,100
1,0,50
更好的可读性:
awk 'BEGIN{
FS=OFS=","
}
{
c1=c2=sum=0; # reset variables
}
$1==3{ # if col1 equal to 3 then
c1=1;
sum+=50
}
$2==1{ # if col2 equal to 1 then
c2=1;
sum+=50
}
{
print c1,c2,sum # print variables
}' input
您能否尝试以下操作,修复OP的尝试。在 GNU
awk
中进行了更正和测试。
awk '
BEGIN{
FS=OFS=","
}
{
s=0
if($1==3){s+=50;$1="1"} else{$1="0"}
if($2==1){s+=50;$1="1"} else{$2="0"}
print $0,s
}' Input_file
修复OP的尝试:
nf
变量。说明: 为上述内容添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section of this program from here.
FS=OFS="," ##Setting FS and OFS as comma here.
}
{
s=0 ##Setting s as 0 here.
if($1==3){s+=50;$1="1"} else{$1="0"} ##Checking if 1st field is 3 then add 50 to s and set 1 to $1 else keep $1 as 0 here.
if($2==1){s+=50;$1="1"} else{$2="0"} ##Checking if 2nd field is 3 then add 50 to s and set 1 to $2 else keep $2 as 0 here.
print $0,s ##Printing line and value of s here.
}' Input_file ##mentioning Input_file name here.
您可以通过将
AWK
设置为 print
来告诉 ORS
不要在每个 ""
之后放置换行符,但随后您需要自己在需要的地方放置换行符。您的代码可能会按以下方式重新编写:
awk '
BEGIN{
ORS="";FS=OFS=","
}
{
nf=NF
s=0 # initialization
if($1==3){print "1,"; s+=50}else{print "0,"}
if($2==1){print "1,"; s+=50}else{print "0,"}
print s
print "\n"
}END{}' file
那么
file
的内容是
3,1
3,2
它将输出:
1,1,100
1,0,50
(在 gawk 4.2.1 中测试)
echo
'3,1
3,2' |
awk 'BEGIN{ __=(_^=FS=OFS=",")+_ } ($++NF = 50 * (($__=!--$__) + ($_ = _==$_-__)))^!_'
1,1,100
1,0,50