bash:对包括前导零的填充的sed处理

时间:2019-04-05 13:19:36

标签: bash sed leading-zero

我正在使用bash脚本循环遍历目录中数组的几组中预定义的文件,以便在文件存在的情况下进行编辑(例如,在第一组中,从0001至0100,在第二组中-从0001至0050等排列的50个文件。

#an array for the groups
systems=(one two three four)

 # loop over the groups
for file in "${systems[@]}"; do  
      i="1"
      # introduce K var because the filles are numbered as 0001 ... 0100
      k=$(printf '%03d' $i)
      while [  $i -le 100 ]; do
        if [ ! -f "${output}/${file}_${k}.pdb" ]; then
          echo 'File '${output}/${file}_${k}.pdb' does not exits!'
          break
        else
          ## edit file via SED
          # to add i-th number on the first string of the file and substitute smth on the last string;
          sed -i -e '1 i\MODEL '$i'' -e 's/TER/ENDMDL/g' ${output}/${file}_${k}.pdb
          ((i++))
        fi
      done
done

此脚本在SED编辑阶段不起作用,但是如果我省略在filles名称中使用前导零并且仅在脚本中使用第i个索引,则一切正常:

 # loop over the groups
for file in "${systems[@]}"; do  
      i="1"
      # put k into comment since filles arranged from 1 to 100 without leading zeros; 
      #k=$(printf '%03d' $i)
      while [  $i -le 100 ]; do
        # the filles arranged from 1 to 100
        if [ ! -f "${output}/${file}_${i}.pdb" ]; then
          echo 'File '${output}/${file}_${i}.pdb' does not exits!'
          break
        else
          ## edit file via SED
          # to add i-th number on the first string of the file
          sed -i -e '1 i\MODEL '$i'' -e 's/TER/ENDMDL/g' ${output}/${file}_${i}.pdb
          ((i++))
        fi
      done
done

2 个答案:

答案 0 :(得分:2)

  

注意:已经进行了几次编辑。

我在这里没有自己的答案-只是编译为单个代码块,并结合jas(应他的要求)和Walter A的答案(很可能遇到了真正的问题-

for file in "${systems[@]}"
do for ((i=1;i<100;i++))
   do printf -v enumerated "${output}/${file}_%04d.pdb" $i 
     if [[ -f "$enumerated" ]
     then sed -i -e "1 i\\MODEL $i" -e 's/TER/ENDMDL/g' $enumerated
     else echo "file not found: '$enumerated''
     fi
  done
done

根据目录结构中的其他内容,您也可以尝试以下操作:

for stub in "${systems[@]}"
do for file in "$output/${stub}"_[0-9][0-9][0-9][0-9].pdb
   do sed -i -e "1 i\\MODEL ${file//[^0-9]/}" -e 's/TER/ENDMDL/g' "$file"
   done
done

答案 1 :(得分:2)

watchk循环之前被分配

i

将分配移至循环内的i="1" # introduce K var because the files are numbered as 0001 ... 0100 k=$(printf '%03d' $i) while [ $i -le 100 ]; do ... ((i++)) ... done
替代:

k