Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate a file and string into a new file in UNIX as a one line command

Tags:

unix

autosys

I need a very simple (hopefully) 1 liner command that reads in a file appends a string and outputs to a new file, without changing the original data.

file1               string
------              ------
apple               oranges
bananas

MAGIC COMMAND

filel               file2
------              ------
apple               apple
bananas             bananas
                    oranges

basically, cat file1 + 'oranges' > file2

I'm using autosys to run the command, and I'm pretty sure it doesn't allow for && or ; as part of a single command.

like image 728
Christian Avatar asked Jul 09 '12 19:07

Christian


People also ask

How do you concatenate files in Unix?

Type the cat command followed by the file or files you want to add to the end of an existing file. Then, type two output redirection symbols ( >> ) followed by the name of the existing file you want to add to.

How do I append data from one file to another in Unix?

You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

Which command is used to concatenate two files Unix?

The join command in UNIX is a command line utility for joining lines of two files on a common field.

Which command is used to concatenate files?

To concatenate files, we'll use the cat (short for concatenate) command.


3 Answers

You can do this:

(cat file1 ; echo 'oranges') > file2

Which will spawn one subshell, which will cat file1 to stdout, then echo oranges to stdout. And we capture all that output and redirect it to a new file, file2.

Or these 2 commands:

cp file1 file2 
echo 'oranges' >> file2

Which first copies file1 to the new file2, and then appends the word oranges to file2

Here's another one liner that does not use ; nor &&

echo oranges | cat file1 - > file2
like image 67
nos Avatar answered Sep 30 '22 21:09

nos


awk '1; END{ print "oranges"}' file1 > file2

You can probably use the standard solution (given by nos) if you pass it as a string to sh:

sh -c 'cat file1; echo oranges' > file2
like image 32
William Pursell Avatar answered Sep 30 '22 22:09

William Pursell


Then this should do it:

$cat file1 >> file2; echo "orange" >> file2;
like image 32
Aftnix Avatar answered Sep 30 '22 22:09

Aftnix