如何用awk提取TYPE含wireless的DEVICE?处理NAME含空格问题
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 ourTYPEfield)~ /wireless/: Checks ifTYPEcontains the substring "wireless"print $NF: Prints the last field (ourDEVICEfield) 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:
- We first grab
UUID,TYPE, andDEVICEfrom the end of the line since their positions are fixed relative to the end. - We extract the
NAMEportion by taking everything before theUUIDstring. - We replace all spaces in
NAMEwith hyphens usinggsub. - We reconstruct the line so
NAMEis a single field, then split it into fields and check if the third field (nowTYPE) 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

