简体   繁体   中英

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

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?

eg 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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