如何提取多文件中双方括号内的字符串?求sed/awk/grep脚本
[[...]]) Got it, let's figure out how to pull out that content inside [[...]] from your files. I've tested a few one-liners with grep, sed, and awk that should work reliably for your use case—even with IPv6 addresses or other special characters inside the brackets.
Using Grep (Most Straightforward)
If your system's grep supports Perl-compatible regular expressions (most modern Linux/macOS versions do with -P), this is the simplest approach:
# Extracts only the content between [[ and ]], no extra characters grep -oP '(?<=\[\[).*?(?=\]\])' your_file.txt
Breakdown:
-o: Only outputs the matched part of the line, not the entire line-P: Enables Perl regex mode for lookaround assertions(?<=\[\[): Positive lookbehind—matches right after[[.*?: Non-greedy match (stops at the first]]instead of the last one)(?=\]\]): Positive lookahead—matches right before]]
If you don't have -P support, use this alternative with basic grep and sed:
grep -o '\[\[.*\]\]' your_file.txt | sed 's/\[\[\(.*\)\]\]/\1/'
Using Sed
For systems where grep's PCRE isn't available, sed works great too:
# Basic version (matches one [[...]] per line) sed -n 's/.*\[\[\(.*\)\]\].*/\1/p' your_file.txt
If a single line has multiple [[...]] entries, use this GNU sed command to extract all of them:
sed -n 's/\[\[\(.*?\)\]\]/\1\n/g; s/.*\n//g; p' your_file.txt
Using Awk
Awk is another solid option, especially if you need to handle multiple matches per line consistently:
awk -F'\\[\\[|\\]\\]' '{for(i=2; i<=NF; i+=2) print $i}' your_file.txt
Breakdown:
-F'\\[\\[|\\]\\]': Sets[[and]]as field separators- The loop prints every even-numbered field (since fields 1,3,5... are the text outside brackets, and 2,4,6... are the content inside)
All these commands will pull out exactly what's inside those double square brackets—whether it's your IPv6 addresses or any other text.
内容的提问来源于stack exchange,提问作者sanky

