如何基于十六进制值对stuff.txt中含TAG的行排序?
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 stringTAG-k 3,3: Tellssortto 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 the0xprefix)
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-
awkpart: Iterates through each field to find the one withTAG, grabs the next field as the hex key, then prints the key + full linesort -k1,1 --hex-number-sort: Sorts using the extracted hex keycut -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 afterTAGstrtonum("0x"m[1]): Converts the hex string to a decimal number for sortingsort -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

