
我正在創建一個shell 腳本來從CSV 文件獲取輸入,有兩行(一列提到時間,另一行文件字串)。 ,而且如何我知道它正在搜索哪一行沒有得到文件。
樣本文件:
1300,N213
1245,N218
1400,N222
1600,N225
程式碼,我正在努力讓它發揮作用。
#!/bin/bash
tr_filepath=/var/opt/data/nms_umts_pms_seg/segment1/
echo "Folder to search for traces ${tr_filepath}"
tr_newpath=/var/opt/ericsson/nms_umts_pms_seg/segment1/edos/4G/
CNTRL_FILE=/home/vx622325/filematch.csv
echo "File Contents of ${CNTRL_FILE} to match with pattern"
for i in $CNTRL_FILE;
do
t=$(cat $i | awk -F"," '{ print $1}')
n=$(cat $i | awk -F"," '{ print $2}')
X=`find "$tr_filepath" -type f -iname "A*."$t"*,*="$n"*.bin.gz"`
echo -e "Traces To Copy \n $X\n" >> /home/vx622325/result_`date +"%d_%m_%Y"`.csv
if [ -d "$tr_newpath" ]; then
y= cp -rp $X $tr_newpath
else
echo "Output folder $tr_newpath not found" > /home/vx622325/result_`date +"%d_%m_%Y"`.csv
fi
done
要搜尋的文件
A20190118.2200+0300-2201+0300_SubNetwork=ONRM_RootMo,SubNetwork=N213,MeContext=N213,ManagedElement=1_rnc_gpehfile_Mp0.bin.gz
A20190118.2200+0300-2201+0300_SubNetwork=ONRM_RootMo,SubNetwork=N213,MeContext=N213,ManagedElement=1_rnc_gpehfile_Mp10.bin.gz
A20190118.2200+0300-2201+0300_SubNetwork=ONRM_RootMo,SubNetwork=N213,MeContext=N213,ManagedElement=1_rnc_gpehfile_Mp11.bin.gz
答案1
簡化的腳本,假設該文件~vx622325/filematch.csv
是簡單的CSV 檔案(不嵌入換行符或逗號):
#!/bin/sh
tr_filepath=/var/opt/data/nms_umts_pms_seg/segment1
tr_newpath=/var/opt/ericsson/nms_umts_pms_seg/segment1/edos/4G
result_out=~vx622325/$( date +'result_%d_%m_%Y.log' )
if [ -d "$tr_newpath" ]; then
printf 'Destination does not exist: %s\n' "$tr_newpath" >"$result_out"
exit 1
fi
set --
while IFS=, read -r a b; do
set -- "$@" -o -name "A*.$a*,*=$b*.bin.gz"
done <~vx622325/filematch.csv
shift # removes the initial "-o"
find "$tr_filepath" -type f \( "$@" \) -exec sh -c '
dest=$1; shift
cp "$@" "$dest"/
printf "Copied: %s\n" "$@"' sh "$tr_newpath" {} + >"$result_out"
read
這使用,以逗號作為字段分隔符,從輸入 CSV 檔案中讀取每條記錄到兩個變數a
和中b
。
這些變數用於建立 OR-name
模式find
。
find
然後用於查找名稱與模式相符的檔案。檔案被批次複製到目標目錄,其名稱記錄在輸出檔案中。
使用 GNU 工具,您可以執行以下操作:
#!/bin/bash
tr_filepath=/var/opt/data/nms_umts_pms_seg/segment1
tr_newpath=/var/opt/ericsson/nms_umts_pms_seg/segment1/edos/4G
printf -v result_out '%s/result_%(%d_%m_%Y)T.log' ~vx622325 -1
if [ -d "$tr_newpath" ]; then
printf 'Destination does not exist: %s\n' "$tr_newpath" >"$result_out"
exit 1
fi
namepats=()
while IFS=, read -r a b; do
namepats+=( -o -name "A*.$a*,*=$b*.bin.gz" )
done <~vx622325/filematch.csv
find "$tr_filepath" -type f \( "${namepats[@]:1}" \) \
-exec cp -t "$tr_newpath"/ {} + \
-printf 'Copied: %p\n' >"$result_out"
答案2
正如 msp9011 所提到的,問題在於
for i in $CNTRL_FILE
其中給出了文件名,您應該給出文件的內容。簡單的方法是準備文件設定內部欄位分隔符號(IFS)如下
while IFS=, read -r column1 column2
do
echo "column1 : $column1, column2 : $column1"
#Take action using input
done < $CNTRL_FILE