0

I have below string which has enter character coming randomely and fields are separated by ~$~ and end with @#&.

Please help me to merge broken line into one.

In below string enter character is occured in address field (4/79A)

-------Sting---------- 23510053~$~ABC~$~4313708~$~19072017~$~XYZ~$~CHINNUSAMY~$~~$~R~$~~$~~$~~$~42~$~~$~~$~~$~~$~28022017~$~ 4/79A PQR Marg, Mumbai 4000001~$~TN~$~637301~$~Owns~$~RAT~$~31102015~$~12345~$~@#&

Thanks in advance. Rupesh

Rupesh
  • 1
  • 1
  • 2

1 Answers1

0

Seems to be a (more or less) duplicate of https://stackoverflow.com/a/802439/3595749

Note, you should ask to your client to remove the CRLF signs (rather than aplying the code below).

Nevertheless, try this:

cat inputfile | tr -d '\n' | sed 's/@#&/@#\&\n/g' >outputfile

Explanation:

  • tr is to remove the carriage return,
  • sed is to add it again (only when @#& is encountred). s/@#&/@#\&\n/g is to substitute "@#&" by "@#&\n" (I add a carriage return and "&" must be escaped). This applies globally (the "g" letter at the end).

Note, depending of the source (Unix or Windows), "\n" must be replaced by "\r\n" in some cases.

William R
  • 37
  • 12
  • Dear William, Thanks for the reply. Now my question is my first column contains numbers and at same time if address like for eg 204/7 occcurs after new line character then how should i handle that to merge line without touching first column, For Eg:- 23510053~$~ABC~$~4313708~$~19072017~$~XYZ~$~ 204/7 Mumbai~$~ – Rupesh Sep 25 '17 at 15:23
  • I don't see your point. My code joins all the lines to provide an unique line (the tr command) then cut it (using sed) when I find "@#&". There is no link with numbers (at the beginning of a line or not). Your address will be a single field. – William R Sep 25 '17 at 15:53
  • Try `echo "String with @#& inside" | sed 's/@#&/@#&\n/g'`. The second `&` has a special meaning: replace character with everything that is matched. I think you want `echo "String with @#& inside" | sed 's/@#&/&\n/g'`. – Walter A Sep 25 '17 at 18:16
  • Sorry, didn't noticed. You just can apply an "\" before "&" to escape the special character. I edited the answer accordingly. – William R Sep 26 '17 at 07:25