0

I'm Trying to use that command on bash variable, but I get error. I think that it is happened because of the {} in the command but I don't know how to solve it.

The command is:

add_Area="awk -F\t '{$1="area" FS $1;}1' OFS='\t'"
Output="$( echo $some_csv_-var | ${add_Area})"

The error is:

awk: 1: unexpected character '''  
fileawk: line 2: missing } near end of file
Chris Davies
  • 116,213
  • 16
  • 160
  • 287
Ravid
  • 11
  • Are you intending $1 refer to your script's positional as determined by your shell, or to the first field of the input row as determined by awk? – DopeGhoti Apr 18 '18 at 21:34
  • 1
    Don't store commands in a string. That's what functions are for. – Gilles 'SO- stop being evil' Apr 18 '18 at 22:19
  • @Gilles that's why I answered this instead of pointing to a duplicate. The whitespace choking is a duplicate without any hesitation. The variable vs function might be but I couldn't see a good match when I looked. – Chris Davies Apr 18 '18 at 22:58
  • @JohnMiliter: that doesn't work either; wordsplit of expanded variables is not at all the same as shell input parsing. You need to use eval and triple-backslash both t-for-tabs and the doublequotes AND dollarsigns within the awk script, which let's just not. – dave_thompson_085 Apr 19 '18 at 04:36

1 Answers1

2

Generally speaking it's not a good idea to embed a command in a variable and then execute the variable. You could use a function for that, though.

First, let's explain what's going on and why you're getting an error. It's all about the order of evaluation.

add_Area="awk -F\t '{$1="area" FS $1;}1' OFS='\t'"

The double-quotes around the string allow the shell to evaluate variables. In this case, the $1 is seen and processed by the shell and it's likely that it's unset. Furthermore, you're trying to put double quotes inside double quotes, which actually means the double-quoted section stops and restarts a little later. The resulting assignment becomes this:

add_Area="awk -F\t '{=area FS ;}1' OFS='\t'"

When you try and run that on the next line, it fails because it's not syntactically correct.

Now let's look at a way of solving what I think you're trying to achieve.

# Declare a function
add_Area() {
    awk -F$'\t' 'BEGIN { OFS = FS } { $1 = "area" FS $1 } 1'
}

# Use the function as if it were a normal command
Output="$( echo "$some_csv_var" | add_Area )"

# Later
echo "$Output"
Chris Davies
  • 116,213
  • 16
  • 160
  • 287