2

The following code gives good output but it is verbose and does not scale well when there are a lot of different "names":

#!/bin/bash

name1="jeff"
name2="david"
name3="kenny"
name4="randy"

for i in {1..3}
do
        for names in "$name1" "$name2" "$name3" "$name4"
        do
        awk '{if($1 > 6) print $2}' "$names"_"$i".txt > "$names"_"$i"_above6.txt
        done
        for names in "$name1" "$name2" "$name3" "$name4"
        do
        awk '{if($1 < 6) print $2}' "$names"_"$i".txt > "$names"_"$i"_below6.txt
        done
done

(So this code processes jeff_1.txt, jeff_2.txt, jeff_3.txt, david_1.txt and so on)

Is there a way to re-write the code to condense the "for names in" lines?

e.g. the code below does not work, but is meant to give an idea as to what I'm looking for:

#!/bin/bash

name1="jeff"
name2="david"
name3="kenny"
name4="randy"

for i in {1..3}
do
        for names in "$name{1..4}" 
        do
        awk '{if($1 > 6) print $2}' "$names"_"$i".txt > "$names"_"$i"_above6.txt
        done
        for names in "$name{1..4}"
        do
        awk '{if($1 < 6) print $2}' "$names"_"$i".txt > "$names"_"$i"_below6.txt
        done
done
Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
Bot75
  • 179
  • 8

1 Answers1

4

Here is an example by using arrays:

NAMES=( "jeff" "david" "kenny" "randy" ) 

for NAME in ${NAMES[@]}; do
    # Do something with NAME
    echo "${NAME}"
done

And here https://linuxize.com/post/bash-arrays/#:~:text=Bash%20supports%20one-dimensional%20numerically,1%20references%20the%20last%20element the documentation.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
  • Obviously new to arrays. If each NAMES has multiple files to be acted upon, (e.g jeff_1.txt, jeff_2.txt, jeff_3.txt,) do each of these files need to be added to the NAMES array individually, or is there a way to call different versions of "jeff" files later? Using your example, how would I change echo "${NAME}" so as to echo jeff_1.txt and jeff_2.txt (without changing the NAMES array)? – Bot75 May 31 '21 at 20:12
  • 1
    Get out of the habit of using ALLCAPS variable names, leave those as reserved by the shell. One day you'll write `PATH=something` and then [wonder why](https://stackoverflow.com/q/27555060/7552) your [script is broken](https://stackoverflow.com/q/28310594/7552). – glenn jackman May 31 '21 at 20:28