You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell中用awk提取含多空格字段并保留空格赋值给变量

Fixing Whitespace Preservation When Assigning Awk Output to a Csh Variable

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:

  1. Your ABC.txt line (tab-separated): A\tA B\tC
  2. Run the corrected assignment: set text = "awk -F '\t' '{print $2}' ABC.txt"
  3. Echo with quotes: echo "$text" → Outputs A B (two spaces intact)

Content of the question originates from Stack Exchange, question author Devin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:55:14