0

I'm currently writing a Linux script using awk to split a given txt file into several small files by columns. My code is as follows

#!/bin/bash
postfix=".txt"
i=0
while [ i -lt 60]
do
colone=`expr $i + 1`
coltwo=`expr $i + 2`
colthree=`expr $i + 3`
colfour=`expr $i + 4`
colfive=`expr $i + 5`
colsix=`expr $i + 6`
filename="$i$postfix"
command="awk '{print $"$colone",$"$coltwo",$"$colthree",$"$colfour",$"$colfive",$"$colsix"}' $1 > $filename"
eval $command
i=`expr $i + 6`
done

I got the error which says

awk: {print mydata.txt,,,,5,6}
awk:              ^ syntax error

Is there any way that I can solve this problem?

Frederica
  • 187
  • 1
  • 7
  • yeah, just run the command instead of `eval`ing it i.e don't save it in a variable at all. Look up how to pass bash vars to awk. Also note that all of the math can be done in awk anyway though. – 123 May 24 '17 at 20:28
  • @123 Any suggestion how to do that? I tried to put the math in awk, like awk '{print $($i+1)}' mydata.txt, but it prints my data in a werid way instead of the correct column. – Frederica May 24 '17 at 20:38
  • `awk -v i=$i '{print $(i+1)}' mydata.txt` – Barmar May 24 '17 at 20:39
  • Aside: See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) ("I'm trying to put a command in a variable, but the complex cases always fail!"), and [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048) ("Eval command and security issues"). And consider modern POSIX sh math syntax; `colone=$(( i + 1 ))` is much more efficient to execute than spawning a subshell (which literally `fork()`s off a new copy of your shell process) just to run an `expr` command in that shell and have it exit. – Charles Duffy May 24 '17 at 20:46

0 Answers0