0

I have a file with country, city and state info, among other information. The content of the file looks something like this: (only the part pertaining to the question shown)

Some lines (rows) of text
...
United States
Memphis, TN 38116-3252
...
More lines of text
...
United States
Austin, TX 78726
...

What I would like to do is add a newline before the zip code or after TN (for example) and also replace the ',' with a newline. But I'm assuming the second part will be easier.

Desired format:

Some lines (rows) of text
...
United States
Memphis
TN
38116-3252
...
More lines of text
...
United States
Austin
TX
78726
...

The end goal is to import the data into a spreadsheet like:

Some info | Country | State | City | Etc.
abc       | United..| Texas | Austi| zcx

I'm open for anything that works sed, awk, etc.

1 Answer 1

1

I would use sed for this:

sed -E 's/, /\n/;s/([A-Z]{2}) /\1\n/' States  
Some lines (rows) of text
...
United States
Memphis
TN
38116-3252
...
More lines of text
...
United States
Austin
TX
78726

The first expression s/, /\n/ searches for a comma followed by a space and replaces with newline.

The second expression s/([A-Z]{2}) /\1\n/ searches for any two uppercase letters followed by a space, and replaces with those letters followed by a newline.


sed --version
sed (GNU sed) 4.2.2
7
  • This is better but still not perfect. Why do you need two expressions as you're already using a backref... ? Oct 29, 2016 at 16:45
  • I don't, but at least for me, this makes it easier to read! Oct 29, 2016 at 16:46
  • Thanks for the answer. This seems to work. Actually I'll see if I can make use of only the last part of the expression first and then look for other options to replace the comma because I just noticed that there's a few commas that shouldn't be replaced with newlines. Oct 29, 2016 at 16:48
  • 2
    Now, do you see why a single expression is better ? 's/, ([[:upper:]]{2}) /\n\1\n/' ensures that only the comma+space that precede the name of state will be replaced by a newline. Oct 29, 2016 at 16:49
  • 1
    So why don't you put @don_crissti 's comment somewhere in your answer so that I can accept it? Oct 29, 2016 at 17:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .