長いgrepパターンを複数行に分割

長いgrepパターンを複数行に分割

スクリプトを読みやすくするために、長いgrepパターンを分割してみました。それは可能ですか?

たとえば、この長い行ではなくbashスクリプトを介して

smartctl -a /dev/sda | grep -Ei "Spin_Retry_Count|Calibration_Retry_Count|Reallocated_Event_Count|Offline_Uncorrectable|Reallocated_Sector_Ct|Current_Pending_Sector|CRC_Error_Count|Multi_Zone_Error_Rate|Temperature|CRC_Error_Count|Runtime_Bad_Block|Erase_Fail_Count|Program_Fail_C|End-to-End_Error" | awk '{print $2" "$10}')

もっと読みやすくするために、このようなものに分けたい。

smartctl -a /dev/sda | grep -Ei "Spin_Retry_Count|"\
                                   "Calibration_Retry_Count|"\
                                   "Reallocated_Event_Count|"\
                                   "Offline_Uncorrectable|"\
                                   "Reallocated_Sector_Ct|"\
                                   "Current_Pending_Sector|"\
                                   "CRC_Error_Count|"\
                                   "Multi_Zone_Error_Rate|"\
                                   "Temperature|"\
                                   "CRC_Error_Count|"\
                                   "Runtime_Bad_Block|"\
                                   "Erase_Fail_Count|"\
                                   "Program_Fail_C|"\
                                   "End-to-End_Error" | awk '{print $2" "$10}')

ベストアンサー1

「backslash-newline-whitespace」シーケンスは単一のスペースに置き換えられ、パターンにスペースを追加します。

Bash配列を使用すると、次のように読みやすいコードを生成できます。

words=(
    "Spin_Retry_Count"
    "Calibration_Retry_Count"
    "Reallocated_Event_Count"
    "Offline_Uncorrectable"
    "Reallocated_Sector_Ct"
    "Current_Pending_Sector"
    "CRC_Error_Count"
    "Multi_Zone_Error_Rate"
    "Temperature"
    "CRC_Error_Count"
    "Runtime_Bad_Block"
    "Erase_Fail_Count"
    "Program_Fail_C"
    "End-to-End_Error"
)
# join the words with pipes
pattern=$( IFS='|'; echo "${words[*]}" )

smartctl -a /dev/sda | grep -Ei "$pattern" | awk '{print $2, $10}'

私たちできるGNU awkはgrepの機能を実行できますが、少し冗長な可能性があるため、パイプラインからgrepを削除します。

smartctl -a /dev/sda | gawk -v p="$pattern" -v IGNORECASE=1 '$0 ~ p {print $2, $10}'

おすすめ記事