【问题标题】:Sed command with regular expression and replace [closed]带有正则表达式的 Sed 命令并替换 [关闭]
【发布时间】:2017-12-28 12:04:53
【问题描述】:

我是 sed 命令和正则表达式的新手。

谁能帮我解释一下下面的命令

 echo "FIXTEST_XYZ             23040/tcp       # 127.0.0.1:23040" | sed -n 's/^FIXTEST_\([A-Za-z0-9]\+\)\s\+\([0-9]\+\)\/tcp\s\+#\s*\([A-Za-z0-9.]\+\):\([0-9]\+\)\s*/\1 \2 \3 \4/p'

感谢您的帮助!!

【问题讨论】:

标签: regex shell unix sed


【解决方案1】:

查看explainshell 获取命令说明。

查看regex101 获取正则表达式解释:

^FIXTEST_([A-Za-z0-9]+)\s+([0-9]+)\/tcp\s+#\s*([A-Za-z0-9.]+):([0-9]+)\s*

FIXTEST_ matches the characters FIXTEST_ literally (case sensitive)
1st Capturing Group ([A-Za-z0-9]+)
    Match a single character present in the list below [A-Za-z0-9]+
    + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
    a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
    0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
\s+ matches any whitespace character (equal to [\r\n\t\f\v ])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group ([0-9]+)
    Match a single character present in the list below [0-9]+
    + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
\/ matches the character / literally (case sensitive)
tcp matches the characters tcp literally (case sensitive)
\s+ matches any whitespace character (equal to [\r\n\t\f\v ])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
# matches the character # literally (case sensitive)
\s* matches any whitespace character (equal to [\r\n\t\f\v ])
3rd Capturing Group ([A-Za-z0-9.]+)
: matches the character : literally (case sensitive)
4th Capturing Group ([0-9]+)
\s* matches any whitespace character (equal to [\r\n\t\f\v ])
Global pattern flags
g modifier: global. All matches (don't return after first match)

第一捕获组匹配:XYZ

第二捕获组匹配:23040

第三捕获组匹配:127.0.0.1

第4捕获组匹配:23040

Bash 标准输出:XYZ 23040 127.0.0.1 23040

【讨论】:

  • 感谢 Ben 的解释。我现在明白了。
猜你喜欢
  • 2020-05-21
  • 1970-01-01
  • 2018-08-22
  • 2015-04-01
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
相关资源
最近更新 更多