The One
The One

Reputation: 2331

How to append content of .txt file to another .txt file line by line?

So i have a 1.txt file with this content

1.1.1.1/0 2.2.2.2/0 9.9.9.9/0

I want to append them to a 2.txt file so it would be like:

......
1.1.1.1/0
2.2.2.2/0
9.9.9.9/0

How should i do that?

Upvotes: 0

Views: 775

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84561

The simple way to do this is to redirect file1 using command-substitution to printf "%s\n" and the result to file2. For example, given:

$ cat file1.txt
1.1.1.1/0 2.2.2.2/0 9.9.9.9/0

You can create the file2.txt you want using a single > (to truncante/create a new file2.txt) to redirect the output to file2.txt, but if you want to append to the original content of file2.txt as stated in your question, use >>, e.g.:

$ printf "%s\n" $(<file1.txt) >>file2.txt

Which results in appending the following to your file2.txt:

$ cat file2.txt
## original content
1.1.1.1/0
2.2.2.2/0
9.9.9.9/0

(this is generically called the printf-trick where printf "%s\n" will rely on word-splitting to split a list into as many newline separated individual words as are in the list. It has many other uses. Be wary, if you have more lines than can be held as arguments by the shell, which if I recall correctly is 32767, this may not work)

Another more standard way is to use tr to translate the spaces into '\n', e.g.

$ tr ' ' '\n' < file1.txt >> file2.txt

will accomplish the same thing. Also note, that instead of using ' ' for a single space, you can use a character class (e.g. [...]) and bash provides the POSIX standard character classes such as alnum alpha ascii blank ... (see man bash for complete list) which can be used within the character class as, e.g [:blank:] to check for all whitespace characters (space tab newline, etc..) instead of just the space. For example:

$ tr '[:blank:]' '\n' < file1.txt >> file2.txt

(same note on create/append >/>>)

You can also use sed to do the same thing, e.g.

$ sed 's/[ ]/\n/g' file1.txt >> file2.txt

The benefit of sed is that is allows you to control the replacement of any number of spaces between your addresses. For example, if there were some variable number of spaces or tabs between the addresses, you could handle that with sed as:

$ sed 's/[ \t][ \t]*/\n/g' file1.txt >> file2.txt

Give them all a try, knowing tr and sed are the more robust solutions, but the printf-trick can come in handy as well.

Upvotes: 3

Related Questions