Вопрос

I have a text file with a list of IDs like this:

123
456
789

I would like to use them in queries to look up more information about these items. So far I have unsuccessfully tried:
awk '{print $1;}' 'pathto/file.txt' | xargs echo "SELECT * FROM table WHERE id='{}');" | mysql -u uname -p database

Это было полезно?

Решение

IDS=$(cat /path/to/file)
IDS=$(echo $IDS | sed 's/\s\s*/,/g')
#or IDS=$(echo $IDS | awk '{$1=$1}1' RS= OFS=,) on OSX
echo "SELECT * FROM table WHERE id in ($IDS)" | mysql -u uname -p database

Line 1 loads the ids into a variable, which allows to replace the line breaks easily in line 2, then replace the whitespace by commas to use an IN () construct.

Edits 1 and 2 see comments

Edit 3

on OSX (which I don't use or have access to) it seems sed doesn't like my regex. As the OP points out, using IDS=$(echo $IDS | awk '{$1=$1}1' RS= OFS=,) as line 2 works around this.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top