good_evening
good_evening

Reputation: 21739

Merging two files with cat without new line

I want to merge two files cat file1 file2 > file3. But it starts with new line. I don't want that. I could use tr to replace all new lines to space, but I can't do that, because there are new lines in files which I don't want to replace.

Upvotes: 13

Views: 26064

Answers (4)

Mohammad Kholghi
Mohammad Kholghi

Reputation: 773

Try this:

user$ echo hi1 > file1       #for example
user$ echo hi2 > file2       #for example
user$ x=$(cat file1 file2)
user$ echo -n $x > file3
user$ cat file3
hi1 hi2                      #no newline is added.

Upvotes: 0

Michał Šrajer
Michał Šrajer

Reputation: 31182

you ca use awk:

awk '(FNR>1){print}' file1 file2

update - how it works:

we ask awk to process two files: file1 and file2. It will print whole record (line) if condition (FNR>1) if true. FNR is a variable defined as:

FNR - The input record number in the current input file.

so, condition (FNR>1) will be true every time, except for the first line of each file. This way we skip first line of each file.

Upvotes: -1

Michał Šrajer
Michał Šrajer

Reputation: 31182

in bash, you can do:

cat <(sed -n '1n;p' file1) <(sed -n '1n;p' file2)

Upvotes: 2

chown
chown

Reputation: 52738

You could use head with -1 as the -c flags parameter and -q

head -c -1 -q file1 file2 > file3

head -c -1 will output everything up to the last 1 byte of the code (in this case the last 1 byte - endline - wont be included). The -q is so the filenames dont get piped to file3 as head does by default when heading multiple files.


Or, as suggested by this answer - bash cat multiple files content in to single string without newlines , pipe it to tr:

tr -d "\n"

Upvotes: 23

Related Questions