0

I have a file which has contents on every line following this format (A, B, C, and D represent text):

A B [C] D

E.g.:

cat Cat [noun] This animal likes to eat mice.
  • The first separator is the first occurrence of a space (" ") on a line.
  • The second separator is the first occurrence of a space followed by a square opening bracket (" [").
  • The final separator is the first occurrence of a square closing bracket followed by a space ("] ").

I want to convert all of the content in this file to a CSV file, where @ is used in place of commas:

A@B@C@D
  • The original file contains many foreign characters in UTF-8.
  • There are no spaces or brackets within the contents of A and B.
  • C sometimes contains spaces, but no brackets inside the two given.
  • D contains anything from spaces, square brackets, etc. and the contents should remain unchanged by the conversion.

How can I convert this file to that format?

3 Answers 3

2

Sounds like a task for regular expressions. The literal brackets make this a bit ugly, but here's one that matches your example text.

^([^ ]+) ([^ ]+) \[([^]]+)\] (.*)$

You'll have to check the regular expression api of whatever language you're writing your code in. For help in creating regexes, I recommend Expresso: http://www.ultrapico.com/Expresso.htm

3
  • 1
    +1 but I'd make the 2nd term be ([^ ]+) since space is the following delimiter Mar 2, 2012 at 12:06
  • Thanks glenn, I missed the rule about no spaces in B. Now it's fixed.
    – OlliM
    Mar 2, 2012 at 15:51
  • How do I use this to convert every line in a file?
    – Village
    Mar 3, 2012 at 0:02
1

You need to perform char substitution. I suggest you use sed with regular expression. This is a piece of code corresponding to your example:

sed -r 's/( |\[|\])+/@/g' file_to_modify.txt > file_for_output.txt

For substituting every column in a specific way, the following form is used:

sed -r 's/([^ ]+) ([^ ]+) \[([^]]+)] (.*$)/\1@\2@\3@\4/g' f1.txt > f2.txt
1
  • This is replacing every space and bracket with "@", when it should only be replacing the first space and the first " [" and " ]".
    – Village
    Mar 3, 2012 at 14:04
1

The string looks like a user-defined csv fomart.
Maybe you can try csv module in python:

$ python3
>>> import csv, io, re
>>> '@'.join(next(csv.reader(io.StringIO(re.sub('[\[\]]', '\034', 'A B [c c c] D')), delimiter=' ', quotechar='\034')))
'A@B@c c c@D'
1
  • When I put some symbols at D, it outputs unusual results. E.g. A B [c c c] D[hello] outputs A@B@c c c@D\x1chello\x1c.
    – Village
    Mar 3, 2012 at 0:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.