1

Trying to replace | by , using awk

$ awk '{gsub("|",","); print}' sample.txt | tee sample.txt

sample file contains ||| characters and target is to replace with ,,, when fired above command the output is ,|,|,| where it should be ,,,

Shriram Panchal
  • 1,996
  • 1
  • 20
  • 23
  • Thanks for sharing your efforts, could you please post samples of input and expected output in your question to make it clear, thank you. – RavinderSingh13 Aug 11 '22 at 03:50
  • sample.txt contains ||| character which I need to replace with ,,, – Shriram Panchal Aug 11 '22 at 03:51
  • You need to escape `|` try like: `awk '{gsub(/\|/,",")} 1' file` once. – RavinderSingh13 Aug 11 '22 at 03:52
  • Do not do `cmd file | tee file` or any other variation of trying to write to the same file you're reading while you're reading it for any command as it's not robust. Instead do `tmp=$(mktemp) && cmd file > "$tmp" && mv -- "$tmp" file`. – Ed Morton Aug 11 '22 at 13:26

1 Answers1

2

Try awk '{gsub(/\|/,","); print}' sample.txt | tee output.txt. Note that "|" need to be escaped with "\", and the result is then "tee"ed to another file. Writing back to the same file may not be safe.

MMZK1526
  • 654
  • 2
  • 16