2

This is a second part of Read from file into variable - Bash Script

I have a bash script that reads strings in a file parses and assigns it to a variable. The file looks like this (file.txt):

database1 table1
database1 table4
database2
database3 table2

Using awk in the script:

s=$(awk '{$1=$1}1' OFS='.' ORS='|' file.txt)
LIST="${s%|}"

echo "$LIST"
database1.table1|database1.table4|database2|database3.table2 

But I need to add some wildcards at the end of each substring. I need this result:

database1.table1.*|database1.table4.*|database2*.*|database3.table2.*

The conditions are: if we read database2 the output should be database2*.* and if we read a database and a table the output should be database1.table1.*

0

3 Answers 3

0

Use this awk with ORS='.*|':

s=$(awk '$0=="database2"{$0=$0 "*.*";print;next} {$2=$2 ".*"}1' OFS='.' ORS='|' file.txt)
LIST="${s%|}"

echo "$LIST"
database1.table1.*|database1.table4.*|database2*.*|database3.table2.*
Sign up to request clarification or add additional context in comments.

6 Comments

This is quite close. But OP is looking for database2*.* instead of database2.*, though I have my doubts on his expected output.
Yes I have same doubt because database2.* appears more correct regex
Thats correct. I'm looking for database2*.* instead of database2.*
@andresg3: How are you going to use database2*.* Do you really want to match 0 or more occurrences of digit 2 using this regex?
Maybe it's a glob, not a regex.
|
0

Assuming the (slightly odd) regex is correct the following awk script works for me on your example input.

BEGIN {OFS="."; ORS="|"}
!$2 {$1=$1"*"}
{$(NF+1)="*"}
1
  1. Set OFS and ORS.
  2. If we do not have a second field add a * to our first field.
  3. Add a * as a final field.
  4. Print the line.

Run as awk -f script.awk inputfile where the above script is in the script.awk (or whatever) file.

1 Comment

@andresg3 That was just the awk script body itself. Sorry if that was unclear.
0

I'd do it like this.

script.sh containing the following code:

#!/bin/bash

while IFS='' read -r line ;do
  database=$(awk '{print $1}' <<< $line)
     table=$(awk '{print $2}' <<< $line)
  if [ "${table}" == '' ] ;then
    list=(${list}\|${database}\*\.\*)
  else
    list=(${list}\|${database}\.${table}\.\*)
  fi
done <file.txt

list=$(cut -c 2- <<< ${list})
echo ${list}

exit 0

file.txt containing the following data:

database1 table1
database1 table4
database2
database3 table2

Script output is the following:

database1.table1.*|database1.table4.*|database2*.*|database3.table2.*

Tested in BASH version: GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.