How to cat two files after each other but omit the

2019-02-12 02:26发布

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?

7条回答
Explosion°爆炸
2楼-- · 2019-02-12 03:15

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]

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-12 03:18
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
查看更多
Evening l夕情丶
4楼-- · 2019-02-12 03:21
$ head --lines=-1 file1 > res
$ tail --lines=+2 file2 >> res
查看更多
Summer. ? 凉城
5楼-- · 2019-02-12 03:21

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

查看更多
Viruses.
6楼-- · 2019-02-12 03:25
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.

查看更多
爷、活的狠高调
7楼-- · 2019-02-12 03:27

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.

查看更多
登录 后发表回答