4

I want to remove a character "[" from a file. I tried

 sed -i 's/[//g' 'filename'

however I get the following error

sed: -e expression #1, char 6: unterminated `s' command

6

Yes, the [ character is special as it starts a [...] group (a bracketed expression).

With sed on OpenBSD, your command gives a more helpful error message:

$ sed 's/[//g'
sed: 1: "s/[//g": unbalanced brackets ([])

To delete all [ characters using sed, escape it:

sed -i 's/\[//g' file

Or put it inside a bracketed expression:

sed -i 's/[[]//g' file

Or, use tr,

tr -d '[' <file >file.new

Also, don't use in-place editing with sed until you know the expression that you are trying out actually works, or you will possibly have to restore your data from backups.

  • I second Kusalananda's observation: The first step while using sed should be to use it with the -e flag like sed -e ... so that one is sure what would happen if the changes were to be made permanent beyond rollback. For example, in your example, you would type sed -e 's/\[//g' 'filename' which would do a dry run and tell you what exactly gets changed. – Hopping Bunny 2 days ago
0

Since the question was originally tagged with awk and for no real good reason:

awk '{gsub(/\[/, "")}1' file >newfile

This will print the file with all [ removed and save it to newfile.

Using gawk you can make edits in place:

gawk -i inplace '{gsub(/\[/, "")}1' file

I wouldn't use either of these though unless you are also using awk to take other actions on the file.

  • 1
    Yeah, I removed the tag since it appeared to have no bearing on the question whatsoever. – Kusalananda Nov 9 at 13:31
  • @Kusalananda: I know, but it's not the worst way to do it. – Jesse_b Nov 9 at 13:41
  • This works, but depending on the OS, awk is a symlink to gawk and it has to be version 4.1 or later for -i inplace. – Nasir Riley Nov 9 at 13:46
  • What I'm saying is that depending on the OS, they are the same thing so it doesn't matter which one is used and that if it's not at least version 41., the -i inplace switch isn't going to work. I'm only suggesting that you add the second thing in particular to your answer so that someone with an earlier version doesn't try to use -i inplace and find that it doesn't work. – Nasir Riley Nov 9 at 14:46
  • The fact that awk may be gawk is sort of moot. Also while the version information is correct I just don't see it that necessary to ensure someone is using <6 year old software on a secondary answer. Non-portable methods are non-portable, if they don't work for you use the portable method. – Jesse_b Nov 9 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.