Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a bash script/grep/sed in order to replace class names with the file name itself

I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

#!/bin/bash

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

like image 656
bonsoup Avatar asked Jan 23 '26 05:01

bonsoup


2 Answers

If you don't need to have a solution is script form, in a terminal, just cd to the directory containing the *.java files and use the following command:

for f in *.java; do sed -i "s/MyCritter/"${f%.*}"/g" "$f"; done

The "${f%.*}" portion of the sed command returns the filename without the extension and uses it to replace MyCritter.

like image 136
user3439894 Avatar answered Jan 24 '26 17:01

user3439894


As others mentioned, there are syntax errors in your code and shellcheck can easily detect those.

One of the alternate ways this can be done is:

#!/bin/bash

dir1="Absolute_path_for_dir"
for f in $dir1/*.java;do
    # Extract name from /path/name.java
    filename=$(basename "$f" .java) 

    # Replace ALL occurrences of MyCritter with filename in file $f
    sed -i "s/MyCritter/$filename/g" "$f"  
done
like image 43
ppp Avatar answered Jan 24 '26 17:01

ppp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!