Skip to main content
2 of 3
added 683 characters in body
John1024
  • 76.4k
  • 12
  • 176
  • 165

Let's take this as a sample input file:

$ cat file
jim|process1|23
bob|process2|5
jim|process3|7

Now, let's create this shell script:

$ cat script.sh
read -p "Please Enter a UserName: " uname
awk -v n="$uname" -F\| '$1==n{total+=$3} END{printf "Total for %s is %s minutes\n",n,total}' file

As an example, let's sum up the time used by jim:

$ bash script.sh
Please Enter a UserName: jim
Total for jim is 30 minutes

How it works

awk implicitly loops through every line in the input file. This script uses two variables: n which is the user name and total which is the running total of minutes used by user n.

  • -v n="$uname"

    This creates an awk variable n and assigns to it the value of the shell variable uname.

  • -F\|

    This tells awk to use | as the field separator

  • $1==n{total+=$3}

    Every time the first field, $1, matches the user name, n, we increment the total total by the amount of the third field, $3.

  • END{printf "Total for %s is %s minutes\n",n,total}

    When we are done reading the file, we print out the result.

John1024
  • 76.4k
  • 12
  • 176
  • 165