Score:0

How to remove specific character from file

za flag

I have a file like this.

[Guest]
[AAD_987d7f2f57d2]
[mhope]
[SABatchJobs]
[svc-ata]
[svc-bexec]
[svc-netapp]
[dgalanos]
[roleary]
[smorgan]

How to remove the '[' and ']' from the file so i can get the output as below

Guest
AAD_987d7f2f57d2
mhope
SABatchJobs
svc-ata
svc-bexec
svc-netapp
dgalanos
roleary
smorgan
Score:2
in flag

Use sed:

sed 's/[][]//g' file
  • The sed command is s/pattern/replacement/modifiers, meaning substitute pattern with replacement. g modifier means globally, otherwise only the first match will be replaced.
  • [...] is a character class, so any character inside the brackets match.
  • ] closes the character class unless its at first place inside. As we want to include that in our character class, we place it first.
  • Replacement is empty in our case.
  • Use sed -i '...' to edit your file in place.

You can also use grep -P like I already suggested in your other question:

grep -Po '\[\K[^]]*' file
Lorenz Keel avatar
gr flag
I was ready to suggest `sed 's/\[\(.*\)\]/\1/' file`, but your answer is more readable and elegant than mine :-)
Lorenz Keel avatar
gr flag
@tcprks if you are interested in applying the modification directly on the file (i.e. overwriting it), you can add a `-i` before `file` (this is true only for the `sed` part of the solution.
pLumo avatar
in flag
thanks, added that suggestion to my notes :-)
Score:2
hr flag

The 'standard' utility to remove specific characters is tr:

NAME
       tr - translate or delete characters

SYNOPSIS
       tr [OPTION]... SET1 [SET2]

DESCRIPTION
       Translate, squeeze, and/or delete characters from standard input, writ‐
       ing to standard output.

So for example

tr -d '][' < file

Unlike GNU sed, tr only reads from and writes to standard streams; however you can simulate "in place" editing using a temporary file:

tmpfile=$(mktemp)
tr -d '][' < file > "$tmpfile" && mv "$tmpfile" file

or with the sponge command from package moreutils:

tr -d '][' < file | sponge file

You could also use awk - for example by splitting lines of the file into fields separated by ] and [ and printing only the second:

awk -F '[][]' '{print $2}' file

You can use the same tmpfile trick to simulate "in place" editing, or with GNU awk (aka gawk), use the inplace module:

gawk -i inplace -F '[][]' '{print $2}' file
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.