I have a text file called sample.text which looks like this

Continent Lat/Lon: 46.07305 / -100.546
Country Lat/Lon: 38 / -98
City Lat/Lon:(37.3845) / (-122.0881)

I want to process this text to get output as follow without using temporary file

Continent Lat/Lon: 46.07305 / -100.546
Country Lat/Lon: 38 / -98
City Latitude: (37.3845) 
City Longitude: (-122.0881)

I don't have control over the values of latitude/longitude.

I have accomplished this using 2 awk scripts

BEGIN { FS=":"}  {print $2} | BEGIN { FS="/"}  {printf "City Latitude:%s\nCity Longitude:%s\n",$1,$2} 

As I want to write the original file, is there any way to do it using

sed -i  

All inputs are appreciated.

  • 1
    You mean like: 's/City.*\(([^)]*)\) \/ \(.*\)/City Latitude: \1\nCity Longitude: \2/' ? – Runium Mar 25 '16 at 5:15
  • 1
    @Sukminder. Yes it works perfectly. Can you explain what you did there? – Swatesh Pakhare Mar 25 '16 at 5:25
  • You need to learn regex (regular expression) learn step by step to be able to understand – Mostafa Ahangarha Mar 25 '16 at 5:36
  • 2
    sed -i actually creates a temp file behind the scenes. – drewbenn Mar 25 '16 at 6:12
sed -i 's,^City Lat/Lon:(\(.*\)) / (\(.*\))$,City Latitude: (\1)\nCity Longitude: (\2),' /path/to/file


  • sed -i 's,foo,bar,' /path/to/file: do sed inplace, replacing foo with bar. N.B. I use , as delimiters here instead of /, so that I can use / in the string without having to escape them.
  • ^City Lat/Lon:(\(.*\)) / (\(.*\))$: find any occurrence of this regex, where ^ and $ are the beginning and end of the line respectively, and each of the two \(.*\) represents a capturing group.
  • City Latitude: (\1)\nCity Longitude: (\2): replace with this string, where \1 and \2 represent the groups captured from the first expression, and \n is a newline.
  • What do you mean by '\1 and \2 represents the groups captured from first expression' ? Can you please explain for me that how these values are gettng generated . – Vineet Sharma Mar 25 '16 at 7:12
  • @VineetSharma The second dot point will twice capture different strings .* with the escaped parens \(...\). That is, the strings .* are matched as normal, and these strings are "captured", to be used later. In this case, they represent the latitude and longitude. Then, in the third dot point, we can re-use these previously captured strings, which will replace the placeholders \1 and \2, which represent the first and second captured group respectively. – Sparhawk Mar 25 '16 at 7:38

Your Answer

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

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