使用shell脚本基于匹配值更新列

时间:2018-04-05 19:19:46

标签: shell scripting

考虑文件A,数据为

111 Apple Red 
112 Orange Orange
113 Mango Yellow 

文件B,数据为

111 Apple Blue
112 Orange Black

预期结果应为文件c

111 Apple Blue 
112 Orange Black
113 Mango Yellow

我尝试使用以下代码

#! /bin/ksh
cd /test/files
file1=`ls abc.dat`
file2=`ls cde.dat`
cat $file1 | while read line
do
  var1 =$18
  var2=$03
  cat $file2 | while read line
  do
     var3=$01
     var4=$02
     if [$var1==$var3];then
        mv -v "$file1" "$(echo $file1 | sed 's/$var2/$var4/g')"
     fi
   done
done
exit 0

但在执行脚本时遇到错误

1 个答案:

答案 0 :(得分:0)

作为评论的代码中的基本问题:

#! /bin/ksh
cd /test/files
file1=`ls abc.dat` # Should be just file1=abc.dat
file2=`ls cde.dat` # Ditto
cat $file1 | while read line # Use More Quotes™ - see https://mywiki.wooledge.org/Quotes
do
  var1 =$18 # Syntax error - remove the space. Also, `$18` refers to the variable with the name `18`, which is not defined. Did you mean to write an awk script to get the 18th column?
  var2=$03
  cat $file2 | while read line
  do
     var3=$01
     var4=$02
     if [$var1==$var3];then # You must have spaces around `[` and `==` (which should be a single `=`) and before `]`
        mv -v "$file1" "$(echo $file1 | sed 's/$var2/$var4/g')"
     fi
   done
done
exit 0