How to cat two files after each other but omit the last/first line respectively?
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 su开发者_JS百科re this can be done in a UNIX shell (or rather, Cygwin). But how?
$ head --lines=-1 file1 > res
$ tail --lines=+2 file2 >> res
I am not able to use the following command on my Mac (more specifically, in a bash shell running in a Terminal window on Mac OS X 10.7.5):
head -n -1 file1
The command above generates the following error message:
head: illegal line count -- -1
It appears negative values for the -n parameter are not accepted in the Mac OS X version of head. However, you can use sed instead:
sed -e '$d' file1
["tail -n +2 file2" appears to work as described above on Mac OS X]
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
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.
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
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.
I often use sed
for head|tail actions:
{ sed '$d' file1; sed '1d' file2; } > combined
精彩评论