0

I am trying to write a shell script that inserts data in postgres:

First Part:

#!/usr/bin/env bash

for f in /folder/*.sql; do
  psql -U postgres -f $f
done

for f in /folder1/*.sql; do
  psql -U postgres -f $f
done

I need to add several conditions on it.

  1. I need to sort file names for folder. Example my folder has files a.sql, c.sql, b.sql

I want to sort them on basis of name so first a.sql should be inserted then b.sql and then c.sql.

  1. For folder1 there exists some unwanted files, i want to ignore them(which is happening now also) and first i want to insert the files having base fields and then other tables.

Example folder1 has 1.sql, a.txt, 3.sql, base.sql.

I do not want to insert a.txt And first base.sql should be inserted and then 1.sql and 3.sql

How to do it via shell script?

1 Answer 1

1

The asterisk wildcard expands to a sorted list, so you can just use one loop:

for f in /folder/*.sql /folder1/base.sql /folder1/?.sql; do
  psql -U postgres -f $f
done

The list is sorted alphabetically, though, and depends on the locale.

The question mark matches just one character, so ?.sql will match both 1.sql and 3.sql. You can also use [0-9]*.sql to match files whose names start with a digit. Under extended globbing (shopt -s extglob), you can even say +([0-9]).sql, so it also matches files with more than one digit (e.g. 124.sql). Note that asciibetically, 10 < 2.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks.If i want to insert all the files except the files that have word - sort in them. And all the files that have word match in them.
What would be the regex?
@EatPayBong: Under extglob, you can use !(word).sql to match everything but word.sql.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.