shell循环读取文件拼接字符串

1 注意通道和重定向的区别

通道会开启子shell,于是通道语句块内的变量修改是无法影响到其外的变量的,故使用重定向;

2 windows文件末尾是/r/n

拼接来自windows系统的文件务必首先注意:

[nash5 camFiles]# cat -A camFiles.ori     
0.863631 -0.269646 -0.425949^M$                                                                                                                     [324/1948]
-0.502824 -0.400104 -0.766214^M$                                               
1.44829 4.57325 -2.46031^M$  

倘若不去调回车字符’\r’(^M),那么多行拼接的结果只能看到最后一行的结果,所以需要首先去掉所有文件里的’\r’字符:

for i in $(ls); do sed -i 's|\r||g' $i; done

3 实例代码:

输入文件:

[nash5 camFiles]# cat tmp.raw 
# Bundle file v0.3
63 66674
4318.92 0 0
-0.999016 0.0442186 0.003457
0.0197872 0.514087 -0.85751
-0.0396951 -0.856598 -0.514456
-0.285562 3.57279 -1.96389

读取成2行:

[nash5 camFiles]# cat tmp.cam
-0.285562 3.57279 -1.96389  -0.999016 0.0442186 0.003457 0.0197872 0.514087 -0.85751 -0.0396951 -0.856598 -0.514456
4318.92 0 0 1 0.5 0.5

调用方式:

sh a.sh tmp.raw

实现代码:

#/usr/bin/bash
i=-1
fcount=0
txtytz=""
matrix=""
focalLend0d1=""
ppxppy="0.5 0.5"
paspect="1"  

#创建中间文件
cat $1 | tail -n +3 $1  > tmp.ori
#从第3行开始读取文件
while read line
do
  # for every 4 lines
  let i=i+1
  echo "-> "$line
  case $i in
    0)
      focalLend0d1=$line
      # echo $focalLend0d1
    ;;
    1)
      matrix=$(echo $matrix" "$line)
      # echo $matrix
    ;;
    2)
      matrix=$matrix" "$line
      # echo $matrix
    ;;
    3)
      matrix=$matrix" "$line
      # echo $matrix
    ;;
    4)
      txtytz=$line 
      # echo $txtytz
    ;;
  esac
  
  if [[ $i == 4 ]]
  then
    pushd $FILE_DIR
    echo $txtytz" "$matrix > tmp.cam
    echo $focalLend0d1" "$paspect" "$ppxppy >> tmp.cam
    # echo $txtytz" "$matrix
    popd
    let i=-1
    let fcount=fcount+1
    txtytz=""
    matrix=""
    focalLend0d1=""
    break
  fi 
done < tmp.ori
rm tmp.ori

猜你喜欢

转载自blog.csdn.net/cxy_hust/article/details/108864958