3

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
...
3
  • 4
    The question title doesn't match the example!? Commented Jan 7, 2013 at 10:50
  • 1
    So if (i) appears elsewhere it should not be replaced, or will it never appear other than as per examples? Commented Jan 7, 2013 at 10:56
  • @ChrisSeymour Since OP hasn’t responded for a long time, I updated the question title. Please consider removing your comment and updating your answer (the best one IMO) to mention that. Commented Dec 12, 2017 at 12:11

6 Answers 6

17

You can get it:

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

Output:

456
Sign up to request clarification or add additional context in comments.

4 Comments

test="123456 abc" echo ${test:3} gives as output 456 abc. I want to obtain 123 abc
@user1835630 that is a different problem from both the title and the example? What do you actually want to do?
then try: echo ${test:0:3} and you will get 123
it's giving me bad substitution
3

Try this.

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

Comments

3

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

Comments

2

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.

Comments

1

Here is a pure bash implementation:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.