I am using ksh.

I have a file temp.txt with some pipe delimited data.


As clear from example, the record ends with a new line character after the data value in the last column.

However, I want the record to end with a pipe delimiter and a new line character as below:


I tried the following commands but still unsuccessful:

tr '\n' '|\n' < temp.txt


sed -i 's/\n/|\n/g' temp.txt

Am I missing something?


Unless you have joined lines, the \n doesn't appear in sed's pattern space: the end-of-line anchor is $.

So with GNU sed:

sed -i 's/$/|/' temp.txt
  • Great. This works. Did not know end-of-line is $ for sed. Thanks! – Vicky May 12 '15 at 14:56
  • May I also add that the ignoring of \n (et al) will even apply to their hexadecimal representation! That means in practice, that sed 's/someregex\x0a/something/' will fail as well, because sed will ignore the control character specified in hex in the regex. I had to learn this the hard way back then, when I had to debug the actual cause why my parser did not operate the expected way. – syntaxerror Jun 17 '15 at 22:23

You can use paste:

$ :|paste -d'|' file - > new_file

or perl:

perl -i.bak -ple '$_.="|"' file
  • +1. Could you explain the paste a bit.. – heemayl May 12 '15 at 15:18
  • 1
    @heemayl: : is no-op and it was piped to paste. paste merge lines from file and stdin (which is empty) with | as delimiter. – cuonglm May 12 '15 at 15:24
  • hmm, excessively clever for my taste (and I love a dash of clever!). How about paste -d'|' file /dev/null ? – glenn jackman May 12 '15 at 18:05
  • @glennjackman: It's ok in this case, but can cause long typing when you need multiple /dev/null, something like this. – cuonglm May 12 '15 at 18:11

With GNU sed, you could replace the end of line with | by using:

sed -i 's/$/|/' temp.txt

That will match the end of the line and "replace" it with |, but of course the line will still end and keep its \n

  • Great. This works. Did not know end-of-line is $ for sed. Thanks! – Vicky May 12 '15 at 14:56
  • The $ end-of-line marker is a regular expression feature, not specific to sed. – glenn jackman May 12 '15 at 18:06

You can use GNU sed:

sed -i 's/.*/&|/' file

Special character & corresponds to the pattern matched in the RHS.

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.