Since it's a constant string you're adding there, using sed comes to mind, with the caveat that the string to add is embedded on sed's command line, so anything processed specially by sed will not be taken as-is. E.g. a /
would taken to terminate the s///
command, and &
would be replaced by the pattern part.
$ str=$(cat file2)
$ sed -e "s/\$/ $str/" file1
abc def hello
ghi jkl hello
See e.g. discussion in: Replace the first occurence of a pattern in a file that may contain a slash
Similarly with awk, though this also isn't as content-agnostic as one might think, since for strings set with -v
, awk processes C-style backslash escapes, so the string foo\tbar
would turn into foo[tab]bar
, which may or may not be what you want.
$ str=$(cat file2)
$ awk -v str="$str" '{print $0 " " str}' < file1
abc def hello
ghi jkl hello
See e.g.: Use a shell variable in awk
Or, I guess you could use other tools too, though this turned out a bit Rube Goldberg-esque. I don't know what led me into making this up:
$ paste file1 <( yes "$(cat file2)" ) | head -n "$(wc -l < file1)"
abc def hello
ghi jkl hello