Search code examples
bashvimquoting

Vim highlights everything in red after a functional line of code making the following lines of code not work


I have a tab separated text file e.g. test.txt containing ^M characters and a missing newline symbol at the end:

Samples  Factor
1        2

Using tr and thread https://unix.stackexchange.com/questions/31947/how-to-add-a-newline-to-the-end-of-a-file , I am able to process this table.

My problem is that in my script the line

tr '\r' '\n' < test.txt | sed -e '$a\' > test_temp
mv test_temp test.txt

makes everything below appear in "red" in vim, and my immediately following code does not run. If I remove the sed -e '$a\' part, everything works.

Do you have an explanation for this? Thanks for your help.


Solution

  • Vim seems to be incorrectly treating the backslash as special, even though backslashes don't do anything inside single quotes. What does :set syntax show? My Vim colors everything correctly with syntax=sh, so perhaps yours isn't treating your file as a shell script. (Interestingly, you may notice that Stack Overflow's syntax highlighter gets it wrong, too.)

    If that's it, try adding a shebang line like #!/bin/bash up top.

    Whatever it is, a simpler way to add a new line at the end is to simply echo one. It gets rid of the inefficiency of sed scanning through the entire input stream to find EOF.

    { tr '\r' '\n' < test.txt; echo; } > test_tmp