简体   繁体   English

Shell 脚本排序

[英]Shell script sorting

I am trying to write a shell script that inserts data in postgres:我正在尝试编写在 postgres 中插入数据的 shell 脚本:

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例如我的文件夹有文件 a.sql, c.sql, b.ZAC5C74B64B4B832AZEF2F181AF5FBAC

I want to sort them on basis of name so first a.sql should be inserted then b.sql and then c.sql.我想根据名称对它们进行排序,所以首先应该插入 a.sql 然后 b.sql 然后 c.ZAC5C2C74B64B458AC2AZ.

  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.对于 folder1 存在一些不需要的文件,我想忽略它们(现在也正在发生),首先我想插入具有基本字段的文件,然后是其他表。

Example folder1 has 1.sql, a.txt, 3.sql, base.sql.示例文件夹 1 具有 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我不想插入 a.txt 并且首先应该插入 base.sql 然后 1.sql 和 3.sql

How to do it via shell script?如何通过 shell 脚本来做到这一点?

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.问号只匹配一个字符,因此?.sql将匹配 1.sql 和 3.sql。 You can also use [0-9]*.sql to match files whose names start with a digit.您还可以使用[0-9]*.sql来匹配名称以数字开头的文件。 Under extended globbing ( shopt -s extglob ), you can even say +([0-9]).sql , so it also matches files with more than one digit (eg 124.sql).在扩展通配符( shopt -s extglob )下,您甚至可以说+([0-9]).sql ,因此它也匹配多于一位的文件(例如 124.sql)。 Note that asciibetically, 10 < 2.注意 asciibetically,10 < 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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