10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bash で配列比較

Posted at

2つの配列から重複している要素だけを取り出すスクリプトメモ

#!/bin/bash

array1=("hoge" "fuga" "foo" "bar" "barbar" "1" "hogehoge" "temp" "varvar")
array2=("varvar" "hoge" "fuga" "foo" "barbar" "2" "123" "tmp" "varvarvar" "1")

echo ${array1[@]}
echo ${array2[@]}

for p in ${array1[@]}; do
  for q in ${array2[@]}; do
    if [ "${p}" = "${q}" ]; then
      array3+=(${p})
    fi
  done
done


echo ${array3[@]}

実行例
./arraycompare.sh
hoge fuga foo bar barbar 1 hogehoge temp varvar
varvar hoge fuga foo barbar 2 123 tmp varvarvar 1
hoge fuga foo barbar 1 varvar
10
9
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?