tags:

views:

71

answers:

2

I try to convert clean columnwise data to tables in tex. I am unable to have "\ \n" at each end of line. Please, see the command at the end.

Data

$ . ./bin/addTableTexTags.sh < .data_3
10.31 & 8.50 & 7.40 
 10.34 & 8.53 & 7.81 
 8.22 & 8.62 & 7.78 
 10.16 & 8.53 & 7.44 
 10.41 & 8.38 & 7.63 
 10.38 & 8.57 & 8.03 
 10.13 & 8.66 & 7.41 
 8.50 & 8.60 & 7.15 
 10.41 & 8.63 & 7.21 
 8.53 & 8.53 & 7.12 

$ cat .data_3 
10.31 8.50 7.40
10.34 8.53 7.81
8.22 8.62 7.78
10.16 8.53 7.44
10.41 8.38 7.63
10.38 8.57 8.03
10.13 8.66 7.41
8.50 8.60 7.15
10.41 8.63 7.21
8.53 8.53 7.12

addTableTexTags.sh

#!/bin/bash

sed -e "s@[[:space:]]@\t\&\t@g" -e "s@[[:space:]]*&*[[:space:]]*\$@\t \\  \\\\n@g" 
 // Tried Escaping "\\" with "/" here and there 
 // but cannot get a line ending with "\\ \n".
+1  A: 

If you want each line to end with a pair of backslashes, a space, another backslash, and an 'n' (followed by the newline), then:

sed 's/$/\\\\ \\n/'

If that's not what you want, please explain what you do want.

Single quotes stop the shell messing with the backslashes. With double quotes, that becomes:

sed "s/\$/\\\\\\\\ \\\\n/"

Yes - 8 backlashes in a row! Fun, isn't it?


Adapting this to the script you quote is hard. The first term uses '\t' but it is not clear whether that is to be a tab or an actual backslash and letter 't'.

sed -e 's@[[:space:]]@\t\&\t@g' \
    -e 's@[[:space:]]*&[[:space:]]*$@\\\\ \\n@g'

If you need actual tabs in the output, I usually type them as tabs (making sure I don't have 'vim' set to expandtabs at the time). If I must have '\t' expanded, then I usually use Perl as I know its rules and different shells have different views on the rules. Note that I dropped the '*' immediately after the '&' in the last match; I think you wanted the '&' added by the previous rule removed.

Jonathan Leffler
+2  A: 

here's a simpler way without too much regex. Just set the output field separator (OFS).

$ awk '{$1=$1}1' OFS=" & " file
10.31 & 8.50 & 7.40
10.34 & 8.53 & 7.81
8.22 & 8.62 & 7.78
10.16 & 8.53 & 7.44
10.41 & 8.38 & 7.63
10.38 & 8.57 & 8.03
10.13 & 8.66 & 7.41
8.50 & 8.60 & 7.15
10.41 & 8.63 & 7.21
8.53 & 8.53 & 7.12

the equivalent of this: awk '{$1=$1}1' OFS=" & " .data | sed -e 's@$@\\\\@g' that you have is.

awk '{$1=$1;$0=$0"\\\\"}1' OFS=" & " file

when you use awk, there's no need to use sed.

ghostdog74
HH
Why is there the dummy-thing "'{$1=$1}1'"?
HH
`$1=$1` forces the records to be "rebuilt". See 3.4 in http://www.gnu.org/manual/gawk/gawk.html. The "1" at the back is just gawk idiom to print the record.
ghostdog74