text-processing – Easiest Way to Add a String at the Beginning of Every Line from Command Line

awkperlsedtext processing

I am looking for a way to add some string to the beginning of every line (same string for every line).
Not something customizable but rather something that will be easy to remember and available on every POSIX-compliant platform (and every shell as well).

Best Answer

You can use sed:

sed -i 's/^/your_string /' your_file

Thanks to Stephane and Marco's comments, note that the -i option isn't POSIX. A POSIX way to do the above would be

sed 's/^/your_string /' your_file > tmp_copy && mv tmp_copy your_file

or perl:

perl -pi -e 's/^/your_string /' your_file

Explanation

Both commands perform a regex substitution, replacing the beginning of a line (^) with your desired string. The -i switch in both commands makes sure the file is edited in place (i.e. the changes are reflected in the file instead of printed to stdout).

sed should be available on any POSIX-compliant OS and perl should be available on most modern Unices except perhaps for the ones that have gone through the effort of removing it.

Related Question