0

I want to store the output of the diff command into an array and to find the length of the array using a Bash script. I tried this, but it didn't work:

arr=( $(diff -w file1 file2 | grep '<' | awk '{print $10}') )

arr=( $(diff -w file1 file2 | grep '>' | awk '{print $10}') )

echo "$arr"
echo "number of files : ${#arr[@]}"
  • 4
    "didn't work" is a useless problem description. What did happen, and how did that differ from what you expected to happen? – glenn jackman Dec 9 '15 at 20:44
1

From what you describe, you don't need an array at all. The length of the array would be equal to the number of words. There's a command for that: wc ("word count").

However, looking at these commands:

arr=( $(diff -w file1 file2 | grep '<' | awk '{print $10}') )
arr=( $(diff -w file1 file2 | grep '>' | awk '{print $10}') )
echo "number of files : ${#arr[@]}"

My guess is that what you really want is: extract column 10 from lines that start with < or >:

files=($(diff -w file1 file2 | awk '/^[<>]/ {print $10}') )

Even better using readarray / mapfile to avoid sub-shells (thanks @kos for the tip):

readarray files < <(diff -w file1 file2 | awk '/^[<>]/ {print $10}')
| improve this answer | |
  • @kos cool, I hope to see you there soon – janos Dec 29 '15 at 12:11

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.