Remove whitespaces between delimiter and characters

Hello All,

I have a pipe delimited file and below is a sample data how it looks:

CS123 | | || 5897 | QXCYN87876 

As stated above, the delimited files contains sometimes only spaces as data fields and sometimes there are extra spaces before/after numeric/character data fields. My requirement is to replace the spaces using the below rule:

  1. If the data field between delimiters doesn't have value then do nothing.
  2. If the data field between delimiters have just spaces then replace the field content with 0
  3. Remove extra trailing/leading spaces before and after any numeric/character data. For eg,
| 5897 | QXCYN87876 

looks like

|5897|QXCYN87876

Any help is appreciated.

Try:-

sed 's#\([|]\)\([ ]*\)\([|]\)#\10\2#;s#\([ ]*\)\([^ ]*\)\([ ]*\)#\2#g' file

Hi Yoda,

Thanks. But the output actually looks like:

CS123|0||5897|QXCYN87876

As it displays, there is a missing data field |0| :- CS123|0|0|
Also, if the text field contains say QXCYN87876 some space then text then the code removes the spaces between the texts also and the result looks like:

CS123|0||5897|QXCYN87876somespacethentext

Sorry to have missed out in the earlier requirement.
Would be great if you can suggest.

Like so?

sed ':L; s/| \+|/|0|/; tL; s/ *| */|/g' file
CS123|0|0||5897|QXCYN87876 some text

Hi amvip,
Your requirements are still a little bit ambiguous...

If there are one or more spaces before the 1st pipe symbol or after the last pipe symbol and there are no characters other than spaces in those fields; are those spaces supposed to be removed, are they supposed to be changed to a single zero character, or are they to be left unchanged? Of your three rules, the first two rules do not apply because the data field is not "between delimiters" and the third rule doesn't apply because there are no characters in the field other than spaces.

The code RudiC suggested in post #4 will turn leading and trailing fields containing only spaces into empty fields. Is that what you want?