Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

linux - Append text to each of multiple lines in file

I have a query which is to be performed on thousands of rows (28,000 odd to be more exact) using a unique identifier. This is (simplified) the query:

update "table1" set event_type = 'NEW' where id=

And there is a file ids.txt which contains the ids for the rows the update is to be performed on:

10003
10009
....
....
79345
79356

The resultant file should be like this:

update "table1" set event_type = 'NEW' where id=10003;
update "table1" set event_type = 'NEW' where id=10009;
...
update "table1" set event_type = 'NEW' where id=79356;

Other than taking the ids.txt file and using vim to form all the 28000 queries using global string substitution, is there an easy way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use something simple like sed:

sed -r 's/^([0-9]*)$/update "table1" set event_type = 'NEW' where id=1/' file
               |     write back using 1 as placeholder
             catch digits in the file

Previous answer

I used an approach based on bash loops, whereas it is a bit overkilling. See a related question: Why is using a shell loop to process text considered bad practice?

Loop like this:

while read id
do
   echo "update "table1" set event_type = 'NEW' where id=${id};"
done < ids.txt

It outputs:

$ while read id; do echo "update "table1" set event_type = 'NEW' where id=${id};"; done < ids
update "table1" set event_type = 'NEW' where id=10003;
update "table1" set event_type = 'NEW' where id=10009;
...
update "table1" set event_type = 'NEW' where id=79345;
update "table1" set event_type = 'NEW' where id=79356;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...