如何在Shell中用awk提取含多空格字段并保留空格赋值给变量
The issue you're facing boils down to how the C shell handles command substitution and variable expansion without quotes. Here's a breakdown of what's happening and how to fix it:
Why Your Original Code Loses Spaces
When you run set text = awk -F "\t" '{print $2}' ABC.txt``, the unquoted command substitution tells csh to split awk's output into "words" using any whitespace (including multiple spaces, tabs, or newlines) as a separator. It then joins those words back together with single spaces before assigning to the text variable. By the time you echo it, the multiple spaces are already gone—even quoting the variable later can't recover them because they were lost during assignment.
The Fix: Quote the Command Substitution
To preserve the exact whitespace from awk's output, you need to wrap the command substitution in double quotes. This tells csh to capture the output as a single, unmodified string.
Use this corrected assignment:
set text = "`awk -F '\t' '{print $2}' ABC.txt`"
Verifying the Result
Now, when you use quoted variable expansion with echo, you'll see the original multiple spaces:
echo "$text" # Output: A B (two spaces between A and B)
Important note: If you run echo $text without quotes, the shell will still split the variable into words and collapse spaces—this is standard shell behavior. To retain the whitespace, always quote the variable when expanding it.
Step-by-Step Example
Let’s walk through it with your ABC.txt:
- Your ABC.txt line (tab-separated):
A\tA B\tC - Run the corrected assignment:
set text = "awk -F '\t' '{print $2}' ABC.txt" - Echo with quotes:
echo "$text"→ OutputsA B(two spaces intact)
Content of the question originates from Stack Exchange, question author Devin

