how to assign a string with multiple white spaces to a variable using awk

179 Views Asked by At

I'm running into issues saving awk output to a variable and preserving the input. I have a tab-delimited file, ABC.txt, with the following format: Field 1 = A, Field 2 = A B <- 2 spaces between the letters A and B, Field 3 = C.

set text = `awk -F "\t" '{print $2}' ABC.txt`

echo $text
A B <- 1 space between the letters A and B,

echo "$text"
A B <- 1 space between the letters A and B,

I need a solution where the variable preserves multiple spaces (I've seen instances where there can be two or three consecutive spaces):

echo $text = A B <- 2 spaces between the letters A and B,

or

echo "$text" = A B <- 2 spaces between the letters A and B,

1

There are 1 best solutions below

4
Fravadona On

In CSH, for keeping the blanks you need to double-quote the variable-expansion and the backticks-expression; a simple case would be:

set text = "`echo 'A  B'`"
echo "$text"
A  B

But unlike POSIX compliant shells, CSH doesn't start a new quoting-context for the command-substitutions (aka. backticks-expressions); once you double-quote it, the escaping rules becomes those of the surrounding double-quotes:

  1. no backslash escaping.
  2. can't use a ".
  3. $ starts a variable-expansion.
  4. ` starts a command-substitution.
  5. etc...?

The way to include those characters as literals inside double-quotes is in fact to append them from outside: close the surrounding double-quotes, append the character (with backslash-escaping or inside single-quotes) and then reopen the double-quotes; the shell will take care of the concatenation for you.

Examples:

echo "..."\""..."
echo "..."\$"..."
echo "..."\`"..."
echo "..."'"'"..."
echo "..."'$'"..."
echo "..."'`'"..."

Both of those output:

..."...
...$...
...`...

What you need to do when double-quoting the command-substitution of awk -F "\t" '{print $2}' ABC.txt is then:

set text = "`awk -F "\""\t"\"" '{print "\$"2}' ABC.txt`"
echo "$text"
A  B

BTW, there's no point in using awk -F "\t", it's easier with awk -F '\t' instead:

set text = "`awk -F '\t' '{print "\$"2}' ABC.txt