Help us understand the problem. What is going on with this article?

角括弧[]を正規表現で置換

角括弧を置換したい

[abc]

"abc"

にしたい。

エスケープすればいいよね?

$ echo [abc] | sed 's/[\[\]]/\"/g' 
[abc]

おや。

正解

こちらによると、

https://serverfault.com/questions/466118/using-sed-to-remove-both-an-opening-and-closing-square-bracket-around-a-string

$ echo [abc] | sed 's/[][]/\"/g' 
"abc"

できた。

理由

はこちら
https://www.gnu.org/software/sed/manual/sed.html#Character-Classes-and-Bracket-Expressions
「sed, a stream editor」

「5.5 Character Classes and Bracket Expressions」
によると、

‘]’
ends the bracket expression if it’s not the first list item. So, if you want to make the ‘]’ character a list item, you must put it first.

ということで、] は最初に配置する必要があるらしい。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした