如何使用shell脚本处理文件中的行?

时间:2014-12-22 14:40:27

标签: bash shell unix

我的文件tool.txt包含

DC OPTIMIZER,b_csw_load_14,s_get_bn_master_14,m_get_bn_master,
DC OPTIMIZER,b_csw_load_14,s_get_cu_qp_zones_14,m_get_qp_zones,
DI_ODS,wf_CSW82_ACTIVITY_DATA_to_ODS,s_m_CSW_BN_MASTER_to_ODS,m_CSW_BN_MASTER_to_ODS,
DI_ODS,wf_CSW82_ACTIVITY_DATA_to_ODS,s_m_CSW_IN_LOCATIONS_to_ODS,m_CSW_IN_LOCATIONS_to_ODS,

在我的剧本中

for i in `tail -n +2 /dssdev/appl/dss/sql/arun/tool.txt`
do
FOLDER=`echo $i|cut -d',' -f1`
WORKFLOW_NAME=`echo $i|cut -d',' -f2`
SESSION_NAME=`echo $i|cut -d',' -f3`
MAPPING_NAME=`echo $i|cut -d',' -f4`
MAPPLET_NAME=`echo $i|cut -d',' -f5`
echo $FOLDER'|'$WORKFLOW_NAME'|'$SESSION_NAME'|'$MAPPING_NAME'|'$MAPPLET_NAME>>tool1.csv
done

我的输出文件包含

DC|DC|DC|DC|DC
OPTIMIZER|b_csw_load_14|s_get_bn_master_14|m_get_bn_master|
DC|DC|DC|DC|DC
OPTIMIZER|b_csw_load_14|s_get_cu_qp_zones_14|m_get_qp_zones|
DI_ODS|wf_CSW82_ACTIVITY_DATA_to_ODS|s_m_CSW_BN_MASTER_to_ODS|m_CSW_BN_MASTER_to_ODS|
DI_ODS|wf_CSW82_ACTIVITY_DATA_to_ODS|s_m_CSW_IN_LOCATIONS_to_ODS|m_CSW_IN_LOCATIONS_to_ODS|

但我的要求是

DC OPTIMIZER|b_csw_load_14|s_get_bn_master_14|m_get_bn_master|
DC OPTIMIZER|b_csw_load_14|s_get_cu_qp_zones_14|m_get_qp_zones|
DI_ODS|wf_CSW82_ACTIVITY_DATA_to_ODS|s_m_CSW_BN_MASTER_to_ODS|m_CSW_BN_MASTER_to_ODS|
DI_ODS|wf_CSW82_ACTIVITY_DATA_to_ODS|s_m_CSW_IN_LOCATIONS_to_ODS|m_CSW_IN_LOCATIONS_to_ODS|

DCOPTIMIZER之间的空格是问题。

2 个答案:

答案 0 :(得分:1)

您是否尝试使用“阅读”阅读这些行?

while read line           
do           
    command           
done < file 

然后你有一条看得见的线,你可以用awk或cut来分割......

答案 1 :(得分:1)

您可以将整个代码编写为

while IFS="," read -r FOLDER WORKFLOW_NAME SESSION_NAME MAPPING_NAME MAPPLET_NAME
do 
echo "$FOLDER|$WORKFLOW_NAME|$SESSION_NAME|$MAPPING_NAME|$MAPPLET_NAME" 
done < input >> tool1.csv

输出为

DC OPTIMIZER|b_csw_load_14|s_get_bn_master_14|m_get_bn_master|
DC OPTIMIZER|b_csw_load_14|s_get_cu_qp_zones_14|m_get_qp_zones|
DI_ODS|wf_CSW82_ACTIVITY_DATA_to_ODS|s_m_CSW_BN_MASTER_to_ODS|m_CSW_BN_MASTER_to_ODS|
DI_ODS|wf_CSW82_ACTIVITY_DATA_to_ODS|s_m_CSW_IN_LOCATIONS_to_ODS|m_CSW_IN_LOCATIONS_to_ODS|