Insert Filename into Multiple Files

Hi,

We have a folder that has files in the following structure

abc.sql
def.sql
efg.sql
.
.
.
xyz.sql

I have to find a certain string (say "test") in each file and replace it with the name of the file. For eg. if "test" is present in abc.sql, I want to replace it with "test abc". If test is present in def.sql, then I want to replace it with "test def"

Try this

#!/bin/bash

awk '{f=FILENAME;sub(/.sql/,x,f);sub(/test/,"test "f)}{print >> FILENAME".new"}' *.sql
for file in *.new
do
  fname=${file%.*}
  mv $file $fname
done

--ahamed

1 Like

I am very new to awk and also this forum. Kindly guide me as to where exactly should i be placing my search and replace terms in the code you've provided. Thank you for your time.

You need to replace "test" in the code given to whatever string you want to replace with. Highlighted in previous post.
Also, please try to understand the code, so that you will also learn.

--ahamed

1 Like

Here is an alternative way that might be easier to understand (and hopefully works):

string=test
for file in *.sql; do
  base=`basename $file .sql`
  sed "s/$string/& $base/g" $file > temp
  mv temp $file
done

If you are kind of new to this, trying to figure out awk syntax is not the best place to start. :slight_smile:

saved my day! Thank you!:b::slight_smile:

---------- Post updated at 04:30 AM ---------- Previous update was at 04:25 AM ----------

How do I ignore the case of my search string? Also I want to exclude files where the filename is already present

awk 'BEGIN{IGNORECASE=1}{f=FILENAME;sub(/.sql/,x,f);sub(/test$/,"test "f)}{print >> FILENAME".new"}' *.sql

--ahamed

If that's addressed to me, to ignore case:

sed "s/$string/& $base/gi" $file > temp

If addressed to other script, ahamed101 already responded.

I don't understand what you mean about excluding files. Can you be more specific?

May I know what the $ in test$ achieves?

@Hanson - What I meant was, if a file already consists of the name of the file, then I do not want to replace anything within that file