简体   繁体   English

bash-解析文件并获取变量

[英]bash - parsing file and getting variables

I've searched and searched on here for an answer, and I think the combination of being a noob at bash, not knowing the right way to do this, and not searching for the right keywords has meant I can't quite get over the last hurdle. 我在这里搜索并寻找答案,我认为成为bash的菜鸟,不知道这样做的正确方法以及不搜索正确的关键字的组合,意味着我无法完全克服最后的障碍。

I am looking to write a script doing some checks on our Netapp System. 我希望编写一个脚本来对我们的Netapp系统进行一些检查。 And I have some difficulties to fulfill the 2 first variables (VAR1 & VAR2)... I tried with cut and awk command but all my tries were unsuccessfully. 而且我在实现两个第一个变量(VAR1和VAR2)方面遇到一些困难...我尝试使用cut和awk命令,但所有尝试均未成功。

I have a text file (LUNS) and it looks like : 我有一个文本文件(LUNS),看起来像:

     #SAN1; SAN2
    abc1:abc1N
    abc2:abc2N 
    a3:a3N 
    abcde4:abcde4N

all the lines are text and numeric stuff. 所有行都是文本和数字的东西。

for each line of the tom file, I would like to do: 对于tom文件的每一行,我想这样做:

  • get the value of the 1st column in VAR1 获取VAR1中第一列的值
  • get the value of the 2nd column un VAR2 获取第二列un VAR2的值
  • run and get a new value VAR3 for a command with VAR1 (it will be the size of the LUN so it will be a numeric value) 运行并为带有VAR1的命令获取新值VAR3(它将是LUN的大小,因此它将是一个数值)
  • run and get a new value VAR4 for a command with VAR2 (same as bellow) 运行并为带有VAR2的命令获取新值VAR4(与下面的相同)
  • compare the numeric values of VAR3 & VAR4 比较VAR3和VAR4的数值

What I did : 我做了什么 :

    cat tom |grep -v "#" |while read ligne ; do 
    VAR1=awk -F ";" '{print $1}'
    VAR2=awk -F ";" '{print $1}'
    specific command to get the numeric VAR3 & VAR4 values.
    #and run the comparaison  like : 
    if [ "$VAR3" -ne "$VAR4" ] 
    then
    echo "PROBLEM"
            if [ "$VAR4" -lt "$VAR3" ] ; then echo $VAR4; rm $VAR4; else echo "call support"; fi
    else 
    echo "Everything is OK"
    fi  

my awk is not working. 我的awk无法正常运作。 i am open to any modification in the config file, or in my way to get the VAR1 & VAR2 variables 我愿意在配置文件中进行任何修改,或者以我的方式来获取VAR1和VAR2变量

Can I have your input on, please? 可以请您提出意见吗?

You should be using 您应该使用

command subtitution $(some command) eg a=$(ls) 命令替换$(some command)例如a=$(ls)

OR 要么

quoting mechanism 报价机制

so for awk to work use either 所以awk可以使用

VAR1=$(awk -F ";" '{print $1}')
VAR2=$(awk -F ";" '{print $1}')

or 要么

VAR1=`awk -F ";" '{print $1}'`
VAR2=`awk -F ";" '{print $1}'`

For one thing, you need to do 一方面,您需要做

VAR1=$(echo $ligne|awk -F ";" '{print $1}')
VAR2=$(echo $ligne|awk -F ";" '{print $2}')

No need to use awk 无需使用awk

Could rewrite the loop like 可以像这样重写循环

#!/bin/bash

while read line;do
    [[ "$line" =~ ^#.*$ ]] && continue
    VAR1=${line%:*}
    VAR2=${line#*:}
    echo $VAR1
    echo $VAR2
done < test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM