0

This question already has an answer here:

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

marked as duplicate by DopeGhoti, Gilles bash Apr 18 '18 at 22:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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 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. – roaima 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 4:36
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"

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