-2

I have a file on my Linux machine with:

1234 | 456 |"abc | xyz"|  fid|

I want to replace the | which is between the " " with a comma. Only the pipe which is in between abc and xyz. This line is a part of a file which contains similar lines, but there can be only one | enclosd in "". Can someone help?

  • 4
    Please edit your question and clarify. Can there be more than one line in the file? If yes, can more than one line match? Can there be multiple | characters inside " "? So can you have 1234 | 456 |"abc | xyz"| fid| "foo | bar" | baz? What should we do in those cases? – terdon Dec 4 '17 at 16:09
  • Yes this is supposed to be a data in a file which contains more than one line in the similar pattern. Also for every line I want the editor to find the | between the double quotes and replace it with the comma. – Poushali Chatterjee Dec 5 '17 at 9:17
  • Please edit your question and clarify as I asked. Give a more complete example and explain whether there can be more than one case per line and if it will always be in the same position on each line. – terdon Dec 5 '17 at 9:31
  • YEs there can be more than one line in the file. In each file there can be more than one line which matches this format. No there should not be multiple | inside " " – Poushali Chatterjee Dec 5 '17 at 11:11
  • For the third time, please edit your question and clarify as I asked. – terdon Dec 5 '17 at 11:14
1
echo '1234 | 456 |"abc | xyz"| fid|' | \
sed 's/\([^|]*|[^|]*|[^|]*\)|/\1,/'

Produces this.

1234 | 456 |"abc , xyz"| fid|

This sed line works by looking for stuff that is not a pipe, a pipe, more stuff that is not a pipe, a pipe, more stuff that is not a pipe, and finally the pipe of interest which is left out of the backreference. It replaces all that with the backrefrence and then, instead of that final pipe, a comma. The rest of the line is left alone.

1

I got answer by below method and clarify the terdon question


echo '1234 | 456 |"abc | xyz"|  fid|' | sed "s:|:,:3"

1

This should work, assuming you want to replace the | between quotes on every line:

sed 's/"\([^"]*\)|\([^"]*\)"/"\1,\2"/' yourfile

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.