1. 程式人生 > >sed 、awk 專案中的shell指令碼使用

sed 、awk 專案中的shell指令碼使用

需求:把查詢中的相關程序名稱改成中文,並不修改原始檔內容
原始檔:
[[email protected] scripts]# cat en_source.txt
system               [ OK ]
Monitor              [ OK ]
Location            [ OK ]
Apple                 [ OK ]
orange               [ NO ]
Automatic         [ OK ]
[

[email protected] scripts]#
最後實現的結果
[[email protected] scripts]# sh en_ch.sh
系統                [ 正確 ]
監控                [ 正確 ]
定位                [ 正確 ]
蘋果                [ 正確 ]
橙子                [ 錯誤 ]
自動測試        [ 正確 ]
[
[email protected]
scripts]#

模擬建立專案中相應的檔案

檔案模擬的是檢視程序狀態生產的檔案/servers/scripts/en_source.txt  

程序中文意思的檔案:/servers/scripts/ch_file.txt

[[email protected] scripts]# cat ch_file.txt
系統
監控
定位
蘋果
橙子
自動測試
 

指令碼實現;

相關知識:awk 的條件判斷,取列;awk 顯示行號awk '{print NF}' 檔名;

sed 替換 sed -i -r "s###g" 

檔案是否存在判斷 [ -f  ${SourcesFile} -a ${CHINA} ] || echo "${SourcesFile} or ${CHINA} file does not exist!"

shell 語言for迴圈語句 實現sed 的迴圈替換
for n in $(awk '{print NR}' ${FileStatus})
do
 CPART="${n}s#(.*)#`sed -n ${n}p ${CHINA}`        `sed -n ${n}p ${FileStatus}` #g"
 sed  -i -r "${CPART}" ${ATSPATH}
done
shell 指令碼:

[[email protected] scripts]# cat en_ch.sh
#!/bin/bash

#定義的檔案所在路徑變數
SourceFile=/servers/scripts/en_source.txt
CHINA=/servers/scripts/ch_file.txt
FileStatus=/servers/scripts/file_status.txt
ATSPATH=/servers/scripts/Atsflie.txt

#判斷檔案是否存在;不存在給出提示
[ -f  ${SourcesFile} -a ${CHINA} ] || echo "${SourcesFile} or ${CHINA} file does not exist!"

#連續執行命令
cat ${SourceFile}>${ATSPATH} && \
awk '{if($3 == "NO"){$3="錯誤"}else if($3 == "OK"){$3="正確"} print $2,$3,$4}' ${SourceFile}>${FileStatus}
for n in $(awk '{print NR}' ${FileStatus})
do
 CPART="${n}s#(.*)#`sed -n ${n}p ${CHINA}`        `sed -n ${n}p ${FileStatus}` #g"
 sed  -i -r "${CPART}" ${ATSPATH}
done
cat ${ATSPATH}