user2954718
user2954718

Reputation: 67

Concatenating file using cat command

I'm new to unix, and i was playing with commands while using cat command, i found unexpected output.

I had.

test and the content of test is
line 1
test2 and the content of test2 is
line 2

This is what i typed.

cat test2>>test>test3

The result is

line 2

so my question is why it's not

line 1
line 2

shouldn't this code concatenate test with test2 and them add it into test3?

Upvotes: 0

Views: 941

Answers (3)

Joni
Joni

Reputation: 111219

When you redirect the standard output stream of a program multiple times like in

cat test2 >>test >test3

the redirections are set up in the order you write. In this case, the shell opens test in append mode and sets it as the the standard output for cat. Then it opens test3 in overwrite mode and sets it as the standard output, overriding the previous redirection.

If test can be opened, the net effect of the entire command is the same as:

cat test2 >test3

That is, line 2 is written to test3. If you want to concatenate test and test2 to test3 you should use:

cat test test2 >test3

or do it in two steps:

cat test2 >>test
cat test >test3

Upvotes: 2

Chelseawillrecover
Chelseawillrecover

Reputation: 2644

Try this and apply to yours:

file1
Hello

file2
Goodbye

cat file1 file2 > fileresult

fileresult
Hello
Goodbye

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

You may try like this:-

cat test1.txt test2.txt > test3.txt

Also check What is Linux cat Command?

If you want to check how Cat command works then you may check this tutorial.

Using >> ensures any prior content of bigcats is preserved. The content of panther is appended to bigcats. If you were to use the > operator here, you would replace the contents of bigcats with the contents of panther. Always use >> when you wish to add to the end of an existing file.

Upvotes: 0

Related Questions