Search code examples
unixcommand-lineutilitiesprepend

Unix command to prepend text to a file


Is there a Unix command to prepend some string data to a text file?

Something like:

prepend "to be prepended" text.txt

Solution

  • sed -i.old '1s;^;to be prepended;' inFile
    
    • -i writes the change in place and take a backup if any extension is given. (In this case, .old)
    • 1s;^;to be prepended; substitutes the beginning of the first line by the given replacement string. 1 means act on the first line, s means replace, ; is the delimiter we've selected for s (/ is a common choice as in s/// but any character can be used) and ^ is the regular expression that matches the beginning of a line

    If you want to add a new line to the beginning of the file, you need to add \n on the replacement as in:

    sed -i.old '1s;^;to be prepended\n;' inFile