1

So I have used awk a few times to add or remove text from each line of a text file. What I would like to learn how to do now is to add some characters to each line in multiple places.

What this is for is for my data tables in latex. For example I might have a file that looks something like this:

mass merror velocity verror
1.0 0.1 2.0 0.2
1.5 0.2 1.0 0.2
2.0 0.3 0.5 0.1

now to display this as a table in latex, I need to add "&" between the columns. I want it to be 2 columns with a +/- symbol separating the error values. It also needs to be in math mode in each value. If you don't know latex don't worry. The output code I want is just this:

\(mass \pm \merror\) & \(velocity \pm verror\) \\
\(1.0 \pm 0.1\) & \(2.0 \pm 0.2\) \\
\(1.5 \pm 0.2\) & \(1.0 \pm 0.2\) \\
\(2.0 \pm 0.3\) & \(0.5 \pm 0.1\) \\

So I want it to add "(" before the first and third column of my data "\pm" before the second column and fourth column of my data, and ")" at the end of the second and fourth column. I already know how to add the \ at the end.

  • 3
    awk '{print "\\("$1" \\pm "$2"\\) & \\("$3" \\pm "$4"\\) \\\\"}' – jthill Nov 18 '13 at 19:43
  • that is not working for me. what I tried to use was awk -F" " '{ print "(" $1 "\pm" $2 ") & (" $3"\pm" $4 ") \\" }' table.txt and it almost gets it, but when I add the extra backslashes it breaks! – Rich Williams Nov 18 '13 at 19:53
  • What does @jthill's solution give you? It prints your expected output on my system. – terdon Nov 18 '13 at 19:55
  • nevermind. I figured it out. thanks very much. I needed \\\\ instead of \\\ haha. – Rich Williams Nov 18 '13 at 19:55
  • @jthill why don't you post that as an answer? – terdon Nov 18 '13 at 19:56
3
awk '{print "\\("$1" \\pm "$2"\\) & \\("$3" \\pm "$4"\\) \\\\"}'
1

The awk way you got in the comments should be perfect. Here's how to do the same thing in Perl:

perl -lane 'print "\\($F[0] \\pm \\$F[1]) & \\(\\$F[2] \\pm \\$F[3]) \\\\"' file 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.