Home > Software engineering >  Bash merge specific file when I call a function
Bash merge specific file when I call a function

Time:12-09

I want to merge multiple file that I create on function call, because I call three time the function on Main

aa_file
aa

bb_file
bb

cc_file
cc

Final output

final_file
aa
bb
cc


function cal () {
# Some operation
while true; do
  read -p "would you like asignment ? on ${var} " yn
  case $yn in
    [Yy]* ) arr_var =("$var"); echo "$var" > $var_file;
    [Nn]* ) break;;
     * ) echo "Please answer yes or no.";;
  esac
# Some operation
done
}

# Main
eval arr_var=()
cal "aa"
cal "bb"
cal "cc"

How make a function that can merge all file

for i in "${arr_var[@]}"
do
   cat $i_file $(i 1)_file > final_file
done

because, when I call only two times the function cal, that I want

# Main
eval arr_var=()
cal "aa"
cal "cc"

final_file
aa
cc

CodePudding user response:

Please correct your question, because it is hard to find out what you want.

However, you can call a function multiple times, and you can merge its output into another file. Like this:

for f in `seq 1 5`
 do
 cat ${f}
 done > output_file

Or even like this:

(
 cal "aa"
 cal "bb"
 cal "cc"
) > output_file

In your version, the final_file gets overwritten in every iteration:

for i in "${arr_var[@]}"
do
   cat $i_file $(i 1)_file > final_file
done

Either change > to >> or move the > outside the loop.

CodePudding user response:

if you use bash, you can do:

arr_var=(aa bb cc)
cat "${arr_var[@]/%/_file}" > final_file
  • Related