1

I have a script that wgets a .txt file and datifies the names.

I'd like to diff the changes between the newest & next-to-newest file.

This is how I am able to select them:

ls -t -l | awk '{print $9}' | head -n1 | tail -n1 | tr -d ' ' | xargs echo FIRST=
ls -t -l | awk '{print $9}' | head -n2 | tail -n1 | tr -d ' ' | xargs echo SECOND=

I wanted to use xargs to feed export to variables, and then simply do diff between them, like

diff $FIRST $SECOND

But the export part doesn't work because of the way xargs is.

I think my whole approach is wrong.

0

This will work, and will handle filenames that contain spaces.

b=`ls -t -1 | head -n2`
first="$(echo "$b" | head -n1)"
second="$(echo "$b" | tail -n1)"
diff "$first" "$second"

This method has the advantage that it only parses the directory listing one time, if the directory you are running this in has lots (many thousands) of files, it could be quicker.

1

Changing your approach very little but getting a working version yields:

first=$(ls -t | head -n1)
second=$(ls -t | head -n2 | tail -n1)
diff "$first" "$second"

The above won't work well on file names with embedded newlines, etc.  To remove that limitation use:

ls -t --quoting-style=shell-always | head -n2 | xargs diff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.