Use bash script / grep / sed to replace the class names with the filename itself

I currently have a directory containing numerous .java files, all with different names. i.e. name.java, name2.java, name3.java

I'm trying to write a script that iterates over all the files in a directory and changes their class names (inside the file) to match the file name itself.

Currently, all .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of a specific java file. I wrote a script to try and replace all MyCritter conditions, but I am not getting any changes in the output. Code freezes after printing echo line for filename:

#!/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 endless loop / gets stuck

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

it runs through the entire code but doesn't update the files.

I have tried other grep options 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 mainly used this site for guidance: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

+3


source to share


3 answers


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

One of the alternative ways to do this can be:



#!/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

      

+2


source


If you don't need to have a script form in the terminal, just cd

into the directory containing the files *.java

and use the following command:

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

      



Part of the "${f%.*}"

command sed

returns the filename without the extension and uses it for replacement MyCritter

.

+2


source


With GNU awk for inplace editing:

awk -i inplace '{gsub(/MyCritter/,FILENAME)} 1' *.java

      

or if you want to remove ".java":

awk -i inplace 'FNR==1{f=FILENAME; sub(/\.java$/,"",f)} {gsub(/MyCritter/,f)} 1' *.java

      

0


source







All Articles