AWK/SED. How to remove parentheses in simple text file

I have a text file looking like this:

(-9.1744438E-02,7.6282293E-02) (-9.1744438E-02,7.6282293E-02) ... and so on.

I would like to modify the file by removing all the parenthesis and a new line for each couple so that it look like this:

-9.1744438E-02,7.6282293E-02
-9.1744438E-02,7.6282293E-02
...

A simple way to do that?

Any help is appreciated,

Fred

2

6 Answers

I would use tr for this job:

cat in_file | tr -d '()' > out_file

With the -d switch it just deletes any characters in the given set.

To add new lines you could pipe it through two trs:

cat in_file | tr -d '(' | tr ')' '\n' > out_file
7

As was said, almost:

sed 's/[()]//g' inputfile > outputfile

or in awk:

awk '{gsub(/[()]/,""); print;}' inputfile > outputfile
2

This would work -

awk -v FS="[()]" '{for (i=2;i<=NF;i+=2) print $i }' inputfile > outputfile

Test:

[jaypal:~/Temp] cat file
(-9.1744438E-02,7.6282293E-02) (-9.1744438E-02,7.6282293E-02)
[jaypal:~/Temp] awk -v FS="[()]" '{for (i=2;i<=NF;i+=2) print $i }' file
-9.1744438E-02,7.6282293E-02
-9.1744438E-02,7.6282293E-02

This might work for you:

echo "(-9.1744438E-02,7.6282293E-02) (-9.1744438E-02,7.6282293E-02)" |
sed 's/) (/\n/;s/[()]//g'
-9.1744438E-02,7.6282293E-02
-9.1744438E-02,7.6282293E-02

Guess we all know this, but just to emphasize:

Usage of bash commands is better in terms of time taken for execution, than using awk or sed to do the same job. For instance, try not to use sed/awk where grep can suffice.

In this particular case, I created a file 100000 lines long file, each containing characters "(" as well as ")". Then ran

$ /usr/bin/time -f%E -o log cat file | tr -d "()"

and again,

$ /usr/bin/time -f%E -ao log sed 's/[()]//g' file

And the results were:

05.44 sec : Using tr

05.57 sec : Using sed

cat in_file | sed 's/[()]//g' > out_file

Due to formatting issues, it is not entirely clear from your question whether you also need to insert newlines.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like