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

如何基于十六进制值对stuff.txt中含TAG的行排序?

Sort Lines Containing "TAG" by Hexadecimal Value in stuff.txt

Got it, let's tackle this problem. You need to sort only the lines containing TAG in your stuff.txt file based on their hexadecimal values—here's how you can do it with standard command-line tools, which are perfect for this kind of task:

Basic Scenario (Fixed Field Position)

If your hex value sits in a consistent field (e.g., the 3rd field in every line with TAG), use grep to filter the relevant lines first, then sort with its built-in hexadecimal sorting option:

grep 'TAG' stuff.txt | sort -k 3,3 --hex-number-sort
  • grep 'TAG' stuff.txt: Pulls only lines that include the string TAG
  • -k 3,3: Tells sort to use only the 3rd field as the sort key (adjust the number to match your actual field position)
  • --hex-number-sort: Treats the key as a hexadecimal number (works with or without the 0x prefix)

Flexible Scenario (Hex Value Follows "TAG")

If the hex value comes right after TAG but isn't in a fixed field (e.g., TAG: 0x1f or random text TAG ff more words), use awk to extract the sort key first, then sort and clean up the output:

grep 'TAG' stuff.txt | awk '{for(i=1;i<=NF;i++) if($i~/TAG/) {key=$(i+1); print key, $0}}' | sort -k1,1 --hex-number-sort | cut -d' ' -f2-
  • awk part: Iterates through each field to find the one with TAG, grabs the next field as the hex key, then prints the key + full line
  • sort -k1,1 --hex-number-sort: Sorts using the extracted hex key
  • cut -d' ' -f2-: Removes the temporary key from the output, leaving only the original sorted lines

For macOS/BSD Systems (No --hex-number-sort)

If you're on a system with BSD sort (like macOS) that lacks the hex-specific flag, convert the hex value to decimal first, sort numerically, then strip the decimal key:

grep 'TAG' stuff.txt | awk '{match($0, /TAG([0-9a-fA-F]+)/, m); dec=strtonum("0x"m[1]); print dec, $0}' | sort -n | cut -d' ' -f2-
  • match($0, /TAG([0-9a-fA-F]+)/, m): Extracts the hex digits immediately after TAG
  • strtonum("0x"m[1]): Converts the hex string to a decimal number for sorting
  • sort -n: Sorts numerically using the decimal value

Custom Adjustments

If your hex value is embedded in the same field as TAG (e.g., TAG0x42), tweak the awk pattern to extract just the hex part:

grep 'TAG' stuff.txt | awk '{match($0, /TAG([0-9a-fA-F]+)/, m); print m[1], $0}' | sort -k1,1 --hex-number-sort | cut -d' ' -f2-

Just adjust the field numbers or regex patterns to match the exact format of your stuff.txt lines, and you're good to go!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:45:58