替换 bash 中两个括号之间的空格和 /

Replace spaces and / between two brackets in bash

我有这个(文本)文件:

[check consumer TAIL_SCE_O_P]
[CheckCo on IEB02]
[CheckSubscribers consumers for ne/os/jms/queue/FT_PN_IN]
[CheckSubscribers consumers for ne/os/jms/queue/SO_IN]
Please do not change/me/thank/you
another bracketless text

我想将空格 ( ) 和 / 替换为括号之间的 -

示例输出:

[check-consumer-TAIL_SCE_O_P]
[CheckCo-on-IEB02]
[CheckSubscribers-consumers-for-ne-os-jms-queue-FT_PN_IN]
[CheckSubscribers-consumers-for-ne-os-jms-queue-SO_IN]
Please do not change/me/thank/you
another bracketless text

我试过这个:

cat output.txt |grep "\[" | sed 's/\ /-/g'

但是改了很多东西。

输入数据:

$ cat output.txt
[check consumer TAIL_SCE_O_P]
[CheckCo on IEB02]
[CheckSubscribers consumers for ne/os/jms/queue/FT_PN_IN]
[CheckSubscribers consumers for ne/os/jms/queue/SO_IN]
Please do not change/me/thank/you
another bracketless text

一个sed解法:

$ sed '/\[/,/]/{s/[ /]/-/g}' output.txt

其中:

  • /\[/ + , + /]/ - 范围的开始是左括号;范围的结尾是右括号
  • {s/[ /]/-/g} - 在范围内用连字符 (-)
  • 替换所有空格 ( ) 和正斜杠 (/)

以上生成:

[check-consumer-TAIL_SCE_O_P]
[CheckCo-on-IEB02]
[CheckSubscribers-consumers-for-ne-os-jms-queue-FT_PN_IN]
[CheckSubscribers-consumers-for-ne-os-jms-queue-SO_IN]
Please do not change/me/thank/you
another bracketless text

您可以使用

sed '/^\[.*]$/s/[[:space:]\/]/-/g' file
# => 
# [check-consumer-TAIL_SCE_O_P]
# [CheckCo-on-IEB02]
# [CheckSubscribers-consumers-for-ne-os-jms-queue-FT_PN_IN]
# [CheckSubscribers-consumers-for-ne-os-jms-queue-SO_IN]
# Please do not change/me/thank/you
# another bracketless text

意思是:

  • /^\[.*]$/ - 查找以 [ 开头并以 ]
  • 结尾的行
  • s/[[:space:]\/]/-/g - 在该行中,将空格或 / 替换为 -.

an online sed demo