Add Multi-Line Content to a Linux File with Add-Content


You have a large number of files to edit that are used by Linux servers. The editing and distributing of these files has to be done on a Windows platform. You want to append some multi-line detail to these files with PowerShell, but the file still needs to be compatible with Linux.

Now, Add-Content with a here string would seem to be a good way to go.

 


$a = @"
#TITLE OF LINE
here is the Unix stuff
"@

Add-Content -Value $a -Path .\linux

 

Unfortunately, because of the way Windows handles a new line, when this file is processed by Linux you'll see ^M at the end of each line in the file. What's going on? Well, the ^M represents 0x0D or carriage return, which you may also know as \r or `r. When you press Enter in Windows you get a new line `n (or \n or 0x0A or ^J) AND a carriage return, i.e. \n\r. This mimics the behaviour of a type writer. In the Unix world you only get the newline character.

How to add a Linux friendly entry with Add-Content?

 


$a = "`n#TITLE OF LINE`n\here\is the\unix\stuff`n"

Add-Content -Value $a -Path .\linux

In Notepad it will appear as a single line, however, in Linux you'll have the desired multi-line output.

 

 

Comments (2)

  1. sed ‘s//yourlinehere\n/’
    works. If you want to repeat this command on a lot of file you can do something like:

    for i in *; do sed -i ‘s//yourlinehere\n/’ “$i”; done
    Probably better (but untested) thanks to @ChrisDown:

    find . -type f -print0 | while IFS= read -r -d ” filename;\
    do sed -i ‘s//yourlinehere\n/’ $filename;\
    done
    https://unix.stackexchange.com/questions/1197/adding-a-line-of-text-to-multiple-files

  2. The key ctrl+ key Alt+ key m= prefix micro we right it like this µ

Skip to main content