sed back reference

I have the following lines, stored in the text file tel2:

Hernandez Darin, Alberto|plaza mayor|13190|Corral de Calatrava|926/448/829
Gomez Badenas, Josefina|calle Sagasta|13190|Corral de Calatrava|926.443.602

My intention is to put the phone number as the start of each line, so I did:

sed 's/\(.*13...|[^|]*\)\(.*\)$/\2\1/' tel2.txt

I got only the first group as the output, ignoring the second captured group. But if I put a \n between \2 and \1, it outputs the second group first, and the first in a new line, so it is not the regex. Is the first group overwriting the second?, am I missing something?

Thanks in advance!

2

1 Answer

Based on comments, the issue is that your file has DOS-style CRLF line endings, and your second capture group is capturing the CR and moving it to the middle of the output pattern, as you can see using cat -et to make the line endings explicit:

$ sed 's/\(.*13...|[^|]*\)\(.*\)$/\2\1/' tel2.txt | cat -et
|926/448/829^MHernandez Darin, Alberto|plaza mayor|13190|Corral de Calatrava$
|926.443.602^MGomez Badenas, Josefina|calle Sagasta|13190|Corral de Calatrava$

A possible solution would be to exclude the CR from the second group:

$ sed 's/\(.*13...|[^|]*\)\(.*\)\r$/\2\1\r/' tel2.txt | cat -et
|926/448/829Hernandez Darin, Alberto|plaza mayor|13190|Corral de Calatrava^M$
|926.443.602Gomez Badenas, Josefina|calle Sagasta|13190|Corral de Calatrava^M$

(if you don't want DOS-style endings in the result, omit the \r in the replacement).


I suspect you don't really want the delimiter at the front - a simpler expression that handles the delimiters more sensibly would be

sed 's/\(.*\)|\([^|]*\)\r/\2|\1\r/'

ex.:

$ sed 's/\(.*\)|\([^|]*\)\r/\2|\1\r/' tel2.txt | cat -et
926/448/829|Hernandez Darin, Alberto|plaza mayor|13190|Corral de Calatrava^M$
926.443.602|Gomez Badenas, Josefina|calle Sagasta|13190|Corral de Calatrava^M$
0

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