Home > Mobile >  Retrieving a list of records from a file and add them to a variable list
Retrieving a list of records from a file and add them to a variable list

Time:06-23

I want to:

  1. Provide a list of certain folders (starting with MG) in a certain path and write this list into a .txt file

    ls | grep MG*.* > tempfile.txt
    

    File.txt contents should be:

    MG-x###1 
    MG-x###2 
    MG-x###3
    
  2. Read the .txt file and take the name of the folders and make them items as part of a list

    listvariables="MG-x###1 MG-x###2 MG-x###3"
    

CodePudding user response:

A simple way to achieve 2. would be to use awk to join everything together.

cat tempfile.txt | awk '{printf $1" "}'

So in your bash script you will have something like this:

listvariables=$(cat tempfile.txt | awk '{printf $1" "}')

CodePudding user response:

In a shell that supports arrays (bash, zsh, ksh), use an array: files=(MG*.*).

If your shell doesn't support arrays, you can still use glob expansion: list=$(echo MG*.*) or list=$(printf '%s\n' MG*.*) etc.

If the reason you want a list is to loop over it, again use glob expansion:

for i in MG*.*; do
    echo "$i"
done

To target directories only, use MG*.*/.

  • Related