Multiplying columns x-end while maintaining file structurecouusaf rr810! cohg c
I have as an input File1 which looks like this:
A,22,1,2,3,4,5
G,26,5,6,7
X,28,10,20,10
I would like to apply an equation to columns 3-end while maintaining file structure. For example if the equation I want use is multiplying by 2 I am looking for the output:
A,22,2,4,6,8,10
G,26,10,12,14
X,28,20,40,20
I attempted to do this with the following command:
awk -F ',' '{for(i=1; i<=NF; i++) if (i >= 3)
print 2*$i
else
print $i }' File1
This provides the correct output but gets rid of all file structure. If of use the actual equation I am looking to use is: 2*(2*($i-1)+1)
Any explanations accompanying a solution is much appreciated since I am still quite new to this!
2 Answers
You just need to set the output field separator (OFS), e.g.:
awk '{ for (i=3; i<=NF; i++) $i*=2 } 1' FS=, OFS=, infile
Output:
A,22,2,4,6,8,10
G,26,10,12,14
X,28,20,40,20
-
Thank you @Thor! This maintains structure as wanted. Now my issue is that using the math function. I see how you are doing simple multiplication but don't see how to apply my more complicated formula 2*(2*($i-1)+1) – DNA_bash 8 hours ago
-
1@DNA_bash hint:
$i *= 2is just shorthand for$i = $i * 2. – Ed Morton 59 mins ago
Perl can tackle like as shown:
$ perl -F, -pale '$_ = join q[,], map { $_ > 1 ? 2*(2*($F[$_]-1)+1) : $F[$_] } 0..$#F' inp.csv
Using another approach:
$ perl -lpe '
/^[^,]*,[^,]*/g; #positions the search engine before the 2nd comma.
s/\\G,\\K([^,]*)/2*(2*($1-1)+1)/ge;
' inp.csv
The desk calculator utility can do it as:
$ < inp.csv tr ',-' ' _' | sed -Ee 's/\\S+/[&]/' |
dc -e "
[q]sq
[44an]s,
[1-2*1+2*]s=
[SM lN1+sN z0<a]sa
[LMnl,x LMnl,x lN2-sN]sb
[LMl=xn lN1<, lN1-dsN0<c]sc
[?z0=q 0sN lax lbx lcx 10an z0=?]s?
l?x
"
These are simple utilities and explanations upon request as these are simple n straightforward codes.
-
There's nothing simple about the syntax of sed or perl :) You need to know quite a bit of perl to understand this code, you're using a lot of perl tricks here. And perl I know well enough to get what you're doing, the
dccommands look like magic incantations! – terdon♦ 42 mins ago -
Your
mapsolution could also be:perl -F, -anE '$,=","; say @F[0 .. 1], map { $_ * 2 } @F[2 .. $#F]'– Thor 4 mins ago