为了使我的脚本更具可读性,我尝试拆分我的长 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
序列“反斜杠-换行符-空白”被单个空格替换,因此您要在模式中添加空格。
使用 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}'
我们能从管道中删除 grep 因为 GNU awk 可以做 grep 所做的事情,但可能有点冗长:
smartctl -a /dev/sda | gawk -v p="$pattern" -v IGNORECASE=1 '$0 ~ p {print $2, $10}'