Michael
Michael

Reputation: 14218

Diff report bash script

I have a text file with lines saying:

File fileA and fileB differ 
File fileX and fileY differ

I need a bash script that goes through the whole file, for each line parses the file names and executes the command diff fileA fileB > fileA.diff

Upvotes: 0

Views: 469

Answers (2)

Shawn Chin
Shawn Chin

Reputation: 86864

This command generates a list of diff commands:

[me@home]$ sed -n 's/File \(.*\) and \(.*\) differ/diff "\1" "\2" > "\1.diff"/p' infile
diff "fileA" "fileB" > "fileA.diff"
diff "fileX" "fileY" > "fileX.diff"

You can execute the generated commands by passing them to bash using process substitution.

[me@home]$ bash <(sed -n 's/File \(.*\) and \(.*\) differ/diff "\1" "\2" > "\1.diff"/p' infile )

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881553

The following command:

awk '/ differ$/ {print "diff "$2" "$4" >"$2".diff"}{}'

will give you a script you can run to do this.

See the following transcript:

pax$ echo 'File fileA and fileB differ
hello
File fileX and fileY differ' | awk '
    / differ$/ {print "diff "$2" "$4" >"$2".diff"}{}'
diff fileA fileB >fileA.diff
diff fileX fileY >fileX.diff

Capture the output, then run it with bash and you'll have what you need.

Note that this won't work well with filenames that have spaces in them - if you have such heinous beasts, you will need to do a little more intelligent parsing.

Upvotes: 1

Related Questions