Monday, February 21, 2022

[SOLVED] How to pass a list of files to bash script with less code

Issue

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

Solution

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.



Answered By - Antonio Petricca
Answer Checked By - Clifford M. (WPSolving Volunteer)