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

如何提取最后一个‘Array of’后的首个单词?现有sed代码处理多维数组失效

Alright, let's tackle this nested "Array of" problem so you can extract the innermost type name no matter how many layers deep the arrays are!

The Problem with Your Current Command

Your existing sed -n 's/.*Array of //p' | cut -d ' ' -f 1 works for single-level arrays, but fails with nested ones because:

  • The sed step only strips up to the first occurrence of "Array of", leaving something like Array of MY_TYPE_T in random.h for nested cases.
  • The cut command then grabs the first word of that leftover string, which is just "Array" instead of your desired type.

Solution 1: Improved sed Command (Concise)

Use a greedy regular expression to match up to the last occurrence of "Array of", then capture the first word immediately after it:

sed -n 's/.*Array of \([^ ]*\).*/\1/p'

How it works:

  • .*Array of : The greedy .* matches every character up to the final "Array of " (since it prioritizes the longest possible match).
  • \([^ ]*\): Captures the first sequence of non-space characters right after that final "Array of" — this is your target type name.
  • .*: Matches everything after the type name to clean up the rest of the line.
  • \1: Replaces the entire line with just the captured type name.

Solution 2: awk Command (More Readable)

If you prefer a more explicit approach that's easier to tweak for edge cases, use awk to scan the line and track the last occurrence of "Array of":

awk '{
    target = ""
    for (i = 1; i <= NF; i++) {
        if ($i == "Array" && $(i+1) == "of") {
            target = $(i+2)
        }
    }
    print target
}'

How it works:

  • We loop through every field (word) in the line.
  • Whenever we find "Array" followed immediately by "of", we set target to the next field (the type name after that "Array of").
  • By updating target every time we hit this pattern, the final value will be the innermost type name (from the last "Array of" in the line).
  • Finally, we print the target value.

Testing Both Solutions

Let’s test with your nested example:

Input: MY_TYPE_A_T -- stuff, other stuff, more stuff, ..., Array of Array of MY_TYPE_T in random.h
Output (from both commands): MY_TYPE_T

They’ll also work for 3+ levels of nesting (e.g., Array of Array of Array of MY_TYPE_X) and single-level cases alike.

内容的提问来源于stack exchange,提问作者lolololol ol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:39:27