Linux diff get only line number in the output

﹥>﹥吖頭↗ 提交于 2020-08-19 10:32:59

问题


I want to use linux diff command to get the following output:

2,4c2,4

I only want to know the line numbers where the files are different. I don't want the actual line on the console.

Eg:

If I will execute the following command: diff file1.txt file2.txt

I would like the following output:

2,4c2,4

I don't want the output:

2,4c2,4
< I need to run the laundry.
< I need to wash the dog.
< I need to get the car detailed.
---
> I need to do the laundry.
> I need to wash the car.
> I need to get the dog detailed.

I went through the manual of diff command but I wasn't able to find any option that would allow me to achieve what I want.


回答1:


Pipe it to grep and only show lines beginning with numbers.

diff file1.txt file2.txt | grep '^[1-9]'



回答2:


pass the flag -f .

-sh-4.1$ cat file1.txt 
 I need to run the laundry.
 I need to wash the dog.
 difdferen line 
 I need to get the car detailed.


-sh-4.1$ cat file2.txt 
 I need to run the laundry.
 I need to wash the dog.
 I need to get the car detailed.

-sh-4.1$ diff -f file1.txt file2.txt 
d3

Edited as per @Barmar comment: for it to work on changed lines .. you can just filter lines with "<" or ">" by asking for the inverse of lines that start with "<" or ">"

First : plain diff :

-sh-4.1$ diff file*
3d2
<  difdferen line 
4a4
>  different line in file2
-sh-4.1$ 

with grep to filter lines that start with < or >

  -sh-4.1$ diff   file* | egrep -v "^<|^> |^-"

3,4d2 5a4

3d2
4a4

simplified version suggested by @Barmar

-sh-4.1$ diff file1.txt file2.txt  | egrep -v  "^[-<>]"
3,4d2
5a4 


来源:https://stackoverflow.com/questions/38229094/linux-diff-get-only-line-number-in-the-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!