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

如何用awk提取TYPE含wireless的DEVICE?处理NAME含空格问题

Solution for Extracting DEVICE When NAME Contains Spaces

The core issue here is that the NAME field can have spaces, which breaks fixed-field indexing in awk. There are two effective approaches to solve this: one that directly targets the fields we care about (TYPE and DEVICE) without modifying NAME, and another that replaces spaces in NAME with hyphens first as you requested.

Approach 1: Directly Extract TYPE and DEVICE (Simplest)

Since UUID, TYPE, and DEVICE are always single-word fields (no spaces), we can rely on their position from the end of the line instead of the start. DEVICE is always the last field ($NF), and TYPE is the second-to-last field ($(NF-1)). This avoids dealing with the variable-length NAME field entirely.

Command:

'$(NF-1) ~ /wireless/ { print $NF }' input.txt

Explanation:

  • $(NF-1): References the second-to-last field (this is our TYPE field)
  • ~ /wireless/: Checks if TYPE contains the substring "wireless"
  • print $NF: Prints the last field (our DEVICE field) when the condition is met

Approach 2: Replace Spaces in NAME First

If you specifically need to replace spaces in NAME with hyphens before processing, we can first isolate the NAME portion, modify it, then reconstruct the line with NAME as a single field.

Command:

{
    # Extract the fixed-position fields from the end
    uuid = $(NF-2)
    type = $(NF-1)
    device = $NF
    
    # Isolate the NAME part (everything before the UUID)
    name_part = substr($0, 1, index($0, uuid) - 1)
    
    # Replace spaces in NAME with hyphens
    gsub(/ /, "-", name_part)
    
    # Reconstruct the line with hyphenated NAME
    new_line = name_part " " uuid " " type " " device
    
    # Split the new line into fields and check TYPE
    split(new_line, fields)
    if (fields[3] ~ /wireless/) {
        print fields[4]
    }
} input.txt

Explanation:

  1. We first grab UUID, TYPE, and DEVICE from the end of the line since their positions are fixed relative to the end.
  2. We extract the NAME portion by taking everything before the UUID string.
  3. We replace all spaces in NAME with hyphens using gsub.
  4. We reconstruct the line so NAME is a single field, then split it into fields and check if the third field (now TYPE) contains "wireless", printing the fourth field (DEVICE) if true.

Both approaches will correctly extract the DEVICE name when TYPE contains "wireless", regardless of spaces in the NAME field.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:17:28