Search code examples
shline-breaks

How to prevent sed from changing linebreaks?


I am changing content of a .js file with a .sh file but there's an unwanted side-effect.

.sh file:

# update file
version="0.1"
file="Test.js"
updated_line="const version = \"$version\";"
sed -i "1s/.*/$updated_line/" $file

Test.js file:

const version = "0";
const moreVars = {};

After running the .sh file the update seems to be successfull but my IDE is complaining that the linebreaks changed from CRLF to LF: Changed linebreaks

How can I make these changes while leaving the linebreaks the way they were?


Solution

  • sed is not linebreak aware, in that sense, CR character is just that CR character. If you want your line to have CR character, you have to add CR character. For sed it's just a character like any other.

    updated_line="const version = \"$version\";"$'\r'
    

    How can I make these changes while leaving the linebreaks the way they were?

    Write a regex that matches CR character on the end of the line if it exists and preserve it.

    s/.*\(\x0d\?\)$/$updated_line\1/