質問

I'm looking for git bash (probably?.. need to be cross-platform) command that takes two filepaths and proceed the following:

  1. diff between two files and add to each one of them absent strings (taken from another). So if I have files A and B, I want to insert (B-A) to A, and (A-B) to B. Order of the lines does matter
  2. print back output in format:
    • first filepath
    • strings that was added to it (in format '+string number:string content', without apostrophes)
    • second filepath
    • strings that was added to it (in format '+string number:string content', without apostrophes)

Is it possible at all? Can someone provide any clues (etc. useful code)?

役に立ちましたか?

解決

You can find the differences between the files by using grep -v -f (with -F to avoid special characters). This will return all the lines that are in file B but not file A, then append those lines to the bottom of file A:

grep -vFf file_A file_B >> file_A

Since you want to output the lines as well, it makes sense to store them in a variable so you don't have to run this more than once (and avoids any issue with running the command after appending to the file and getting a different result). Then you can loop through that variable and print out each line with a number:

#!/bin/bash
missing_from_A=$(grep -vFf "$1" "$2")
missing_from_B=$(grep -vFf "$2" "$1")
[[ -n "$missing_from_A" ]] && echo "$missing_from_A" >> "$1"
[[ -n "$missing_from_B" ]] && echo "$missing_from_B" >> "$2"

i=0
echo "First file: $1"
while read line; do
    [[ -n "$line" ]] && printf "+%s:%s\n" $((i+=1)) "$line" || echo "No missing lines found"
done <<< "$missing_from_A"

i=0
echo "Second file: $2"
while read line; do
    [[ -n "$line" ]] && printf "+%s:%s\n" $((i+=1)) "$line" || echo "No missing lines found"
done <<< "$missing_from_B"

Then call your script with the files to run as arguments:

$ ./my_script.sh /home/user/file1.txt /home/user/file2.txt

Example output (and of course, the files are also amended):

First file: file1.txt 
+1:second line in f2
+2:fourth line in f2
Second file: file2.txt
+1:second line in f1
+2:fourth line in f1
+3:fifth line in f1
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top