What is the easiest way to add a string on the beginning of every line of the file from the command line?
:|paste -d'foo ' - - - - input > output
(just kidding, though you'll probably find it's the fastest of all the solutions posted here :-b).
The canonical way is:
sed 's/^/foo /' < input > output
However, it's not easily adapted to arbitrary strings. For instance,
sed "s/^/$var /"
Only works if $var
doesn't contain, &
, \
, /
nor newline characters.
In that regard,
export var
awk '{print ENVIRON["var"], $0}'
or
perl -pe '$_="$ENV{var} $_"'
would work better.
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.
I present a solution using awk
prepending the string “foo”.
awk '{ print "foo", $0; }' input > output
awk
is cross-platform and available on any POSIX system. It does not do in-place editing. If you want to edit a file without creating a second one, you will have to use a temporary file. See Joseph's sed
answer, it shows the syntax. Another hack is to use the following syntax, which is basically creating a temporary file with the same file name as the original file.
{ rm file; awk '{ print "foo", $0 }' > file; } < file