Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK: search and replace

Status
Not open for further replies.

IMAUser

Technical User
May 28, 2003
121
CH
I have a text file with which, besides other things contains lines like

ADD CONSTRAINT ADRA_UK UNIQUE (ADRA_ADRA_ADRACD, ADRA_MND_MNDCD)
...
...
ADD CONSTRAINT ADR_ADRA_FK FOREIGN KEY (ADR_ADRA_AACD, ADR_MND_MNDCD)
...
...
CREATE INDEX ADR_ADRA_FK
ON ADRESSE$ (ADR_ADRA_AACD, ADR_MND_MNDCD)
....

I need to reverse the order of columns in there. So finally the three commands above should read like

ADD CONSTRAINT ADRA_UK UNIQUE (ADRA_MND_MNDCD, ADRA_ADRA_ADRACD)
...
...
ADD CONSTRAINT ADR_ADRA_FK FOREIGN KEY (ADR_MND_MNDCD, ADR_ADRA_AACD)
...
...
CREATE INDEX ADR_ADRA_FK
ON ADRESSE$ (ADR_MND_MNDCD, ADR_ADRA_AACD)
....

I started doing it via a normal K-shell script and I am one third there, i.e. out of the three stmts I can now convert the first one. The script is as below....

for i in `ls -1 *.sql`
do
echo $i
old_text=`grep "ADD CONSTRAINT" $i | grep "_UK" | grep "MNDCD" `
constraint_name=`echo $old_text | awk ' {print $3 } ' `
echo $constraint_name
col_names=`grep "ADD CONSTRAINT" $i | grep "_UK" | grep "MNDCD" | nawk -F"(" ' { print substr($2,1,match($2,"\\\)")-1) } ' `

# echo $col_names

v=0
k=0
for j in $col_names
do
my_array[k]=`echo $j | sed 's/,//g' `
let v=$v+1
let k=$k+1
done

k=0

if [ $v -eq 2 ]
then

new_text="ADD CONSTRAINT $constraint_name UNIQUE ( ${my_array[1]} , ${my_array[0]} ) "

fi
sed "s/$old_text/$new_text/g" $i > $i.tmp
done


As you can see its not as neat and clean. Also, I will need to repeat the same thing for the second command, but since the third command is split across two lines there is no way I can grep the third command from the file.

There are 150 such sql files and it would be a hell of a task to open each one.

Please, Is there a way of doing it in AWK.

Many thanks.
 
How about,
Code:
for i in '*.sql'; do
  sed '
/_[FU]K/{
  /_FK$/ N
  s/(\([^,]*\), \([^)]*\)/(\2, \1/
}
' $i > $i.tmp
done

Cheers,
ND [smile]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top