user1835630
user1835630

Reputation: 261

How can I remove a substring of a string in a shell script?

I have a file with a list of words like:

FIRST_WORD abc
FIRST_WORD(1) bcd
FIRST_WORD(2) def
SECOND_WORD gh
THIRD_WORD jiu
THIRD_WORD(1) lom
...

and I want to remove the (i), when it is present, to obtain:

FIRST_WORD abc
FIRST_WORD bcd
FIRST_WORD def
SECOND_WORD gh
THIRD_WORD jiu
THIRD_WORD lom
...

Upvotes: 3

Views: 25114

Answers (6)

Leon S.
Leon S.

Reputation: 3687

I'd generally go with sed for replacing in files as it is built specifically for that, but in case someone needs to do this operation inside a longer bash script, you can also use bash's search and replace syntax ${var//search/replace}.

while read -r line; do
  echo "${line//(*)/}"
done < ./in.txt

Upvotes: 0

Josh Cartwright
Josh Cartwright

Reputation: 801

Here is a pure bash implementation:

while read -r a b; do
    echo "${a%(*)}" "$b"
done < input.txt

Upvotes: 1

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed -r '$!N;s/^((\S+).*\n\2)\([^)]*\)/\1/;P;D' file

However it might be overkill, if:

sed 's/([0-9]\+)//' file

is suffice.

Upvotes: 2

Chris Seymour
Chris Seymour

Reputation: 85795

Global replacement of all digits strings found inside parenthesis using sed:

$ sed 's/([0-9]\+)//g' file
FIRST_WORD abc
FIRST_WORD bcd
FIRST_WORD def
SECOND_WORD gh
THIRD_WORD jiu
THIRD_WORD lom

# Save the changes back to the file  
$ sed -i 's/([0-9]\+)//g' file

Removing the first 3 characters using sed:

$ sed 's/^...//' file
ST_WORD abc
ST_WORD(1) bcd
ST_WORD(2) def
OND_WORD gh
RD_WORD jiu
RD_WORD(1) lom

Upvotes: 3

jgr
jgr

Reputation: 3974

Try this.

sed 's/([0-9])//g' file

Upvotes: 3

arutaku
arutaku

Reputation: 6087

You can get it:

test="123456"
echo ${test:3}

Output:

456

Upvotes: 17

Related Questions