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
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI 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
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.
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
Nov 13 '19 at 4:43
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.
awk
is a symlink to gawk
and it has to be version 4.1 or later for -i inplace
.
– Nasir Riley
Nov 9 '19 at 13:46
-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 '19 at 14:46
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 '19 at 14:50