Incrementing a variable inside a Bash loop

后端 未结 8 452
挽巷
挽巷 2020-12-29 18:32

I\'m trying to write a small script that will count entries in a log file, and I\'m incrementing a variable (USCOUNTER) which I\'m trying to use after the loop

相关标签:
8条回答
  • 2020-12-29 18:39
    USCOUNTER=$(grep -c "^US " "$FILE")
    
    0 讨论(0)
  • 2020-12-29 18:48

    You are using USCOUNTER in a subshell, that's why the variable is not showing in the main shell.

    Instead of cat FILE | while ..., do just a while ... done < $FILE. This way, you avoid the common problem of I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?:

    while read country _; do
      if [ "US" = "$country" ]; then
            USCOUNTER=$(expr $USCOUNTER + 1)
            echo "US counter $USCOUNTER"
      fi
    done < "$FILE"
    

    Note I also replaced the `` expression with a $().

    I also replaced while read line; do country=$(echo "$line" | cut -d' ' -f1) with while read country _. This allows you to say while read var1 var2 ... varN where var1 contains the first word in the line, $var2 and so on, until $varN containing the remaining content.

    0 讨论(0)
  • 2020-12-29 18:52

    You're getting final 0 because your while loop is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.

    Correct script:

    while read -r country _; do
      if [ "US" = "$country" ]; then
            ((USCOUNTER++))
            echo "US counter $USCOUNTER"
      fi
    done < "$FILE"
    
    0 讨论(0)
  • 2020-12-29 18:54

    Incrementing a variable can be done like that:

      _my_counter=$[$_my_counter + 1]
    

    Counting the number of occurrence of a pattern in a column can be done with grep

     grep -cE "^([^ ]* ){2}US"
    

    -c count

    ([^ ]* ) To detect a colonne

    {2} the colonne number

    US your pattern

    0 讨论(0)
  • 2020-12-29 18:56

    minimalist

    counter=0
    ((counter++))
    echo $counter
    
    0 讨论(0)
  • 2020-12-29 19:00

    Using the following 1 line command for changing many files name in linux using phrase specificity:

    find -type f -name '*.jpg' | rename 's/holiday/honeymoon/'
    

    For all files with the extension ".jpg", if they contain the string "holiday", replace it with "honeymoon". For instance, this command would rename the file "ourholiday001.jpg" to "ourhoneymoon001.jpg".

    This example also illustrates how to use the find command to send a list of files (-type f) with the extension .jpg (-name '*.jpg') to rename via a pipe (|). rename then reads its file list from standard input.

    0 讨论(0)
提交回复
热议问题