2017-04-07 48 views
0

更换线我有2个文件table.cols和table.rulesUnix文件合并 - 如果key存在与价值

table.cols:

column_1 
column_2 
column_3 
column_4 
column_5 

table.rules:

column_3 my_function(column_3, another_parameter) 
column_4 my_other_function(column_3, a_different_parameter) 

我想合并这些文件来生成:

column_1, 
column_2, 
my_function(column_3, another_parameter), 
my_other_function(column_3, a_different_parameter), 
column_5 

注意除最后一行以外每行结尾的逗号。

回答

0

试试这个 -

$ head file? 
==> file1 <== 
column_3 my_function(column_3, another_parameter) 
column_4 my_other_function(column_3, a_different_parameter) 

==> file2 <== 
column_1 
column_2 
column_3 
column_4 
column_5 
$ awk -v line=$(wc -l < file2) 'NR==FNR{a[$1]=$2FS$3;next} {print (a[$1] ?a[$1]OFS :((FNR<line)?$0 OFS:$0))}' OFS=, file1 file2 
column_1, 
column_2, 
my_function(column_3, another_parameter), 
my_other_function(column_3, a_different_parameter), 
column_5 

解释:

((FNR<line)?$0 OFS:$0)) : to ignore the comma from last line. 
0

这个脚本按预期工作:

#! /bin/sh 

OIFS="$IFS" 
IFS=$'\n' 
NL=$(cat table.cols| wc -l) 
CL=1 

rm -f /tmp/tablecols /tmp/tablerules 

for LINE in $(cat table.cols) 
do 
    echo -ne "${LINE}" >> /tmp/tablecols 
    if [ $CL -lt $NL ]; then 
     echo "," >> /tmp/tablecols 
     CL=$((CL + 1)) 
    else 
     echo "" >> /tmp/tablecols 
    fi 
done 

for LINE in $(cat table.rules) 
do 
    KEY=$(echo $LINE|cut -f 1 -d " ") 
    VAL=$(echo $LINE| cut -f 2-5 -d " ") 
    sed -i "s/${KEY}/${VAL}/g" /tmp/tablecols 
done 
mv /tmp/tablecols result 

希望它能帮助! :)

0
join -a1 table.cols table.rules | sed -e 1,4s/$/,/ 
  • 加入到合并文件
  • -a FILENUM打印unpairable线
  • sed命令有一个可选的范围
  • 替代结束符合,