views:

55

answers:

5

I have two files I want to cat together. However, the last line of the first file and the first line of the last file should be omitted.

I am sure this can be done in a UNIX shell (or rather, Cygwin). But how?

+2  A: 

you can use:

head -n -1 file1 && tail -n +2 file2

head shows the first lines of a file, the param -n shows the first n lines of the file, but if you put a - before the number, it shows all the file except the last n lines.

tail is analog..

for better reference:

man head

man tail

Marco
tail +1 includes the first line. it should be +2.
Frank
yeah, I've posted and then tested :P
Marco
strangely, `tail -n -1` has the same effect as `tail -n +2`
BastiBechtold
+1  A: 
$ head --lines=-1 file1 > res
$ tail --lines=+2 file2 >> res
Frank
+1  A: 

The following transcript shows how to acheive this:

pax> cat file1.txt
1.1
1.2
1.3
1.4
1.5

pax> cat file2.txt
2.1
2.2
2.3
2.4
2.5

pax> head --lines=-1 file1.txt ; tail --lines=+2 file2.txt
1.1
1.2
1.3
1.4
2.2
2.3
2.4
2.5

Giving the head command a negative count goes up to that far from the end. Similarly, a count starting with + causes tail to start at that line rather than a certain number of lines from the end.

paxdiablo
+1  A: 
head -n -1 file1

will print all lines in file1 except the last line.

tail -n +2 file2

will print all lines in file2 except the first line.

Combine the two as:

head -n -1 file1 ; tail -n +2 file2
codaddict
+2  A: 
awk 'FNR>2{print p}{p=$0}' file1 file2

Explanation as requested:

FNR is the current record number of the current file being processed. At the start of each iteration, the line is stored in "p" variable, but it is not printed out, yet. As the record number reaches 3, the variable "p" is printed out, which contains record 2. This means the 2nd line. As awk reaches end of file, the last line is not printed out and then it goes to the next file.

ghostdog74
ghostdog74 enlighten us with whats going on here :)
codaddict
Doesn't that remove the first and last lines from _both_ files? Question was for last line of first file and first line of second file, was it not?
paxdiablo