Suppose I have a file, test.java

It starts off like this every line

/*     */ package com.a;
/*     */ import java.util.List

/*     */ etc

I want to remove the first 10 characters from every line and replace with empty space, so after running the command, the file should look like this:

package com.a;
import java.util.List



          package com.a;
          import java.util.List


Thank you

I'm looking for the correct command, and the command should cover every single .java file in all subdirectories below.

  • Note that it's safer to remove every empty commentary at the beginning of a line (regexp ^/\* *\*/) instead of blindly removing the first 10 characters. Even if you are sure that all lines in all files start this way. If you accidently start the script twice, all your code will be ruined. – Philippos Oct 19 '17 at 8:01
  • @Kusalananda I know I use stack exchange frequently, I am familiar with the rules. It's just that I didn't come on the rest of the day – K Split X Oct 19 '17 at 22:23

If you assured about the first 10 characters - use the following find + sed solution:

find . -type f -name "*.java" -exec sed -i 's/.\{10\}//' {} \;

  • find . -type f -name "*.java" - to find all *.java files recursively

  • sed -i 's/.\{10\}//' - remove the 1st 10 characters from each line in each found file (-i option allows to modify the file in-place)

  • this solution will work with GNU sed. With BSD sed you need -i '', as -i requires an argument there. With other versions of sed you don't have -i at all and need to save the output to a different file and mv that file to the original name afterwards.

  • 1
    @KSplitX In this case you are supposed to mark the helpful answer as solution, so future readers will know which answer worked. – Philippos Oct 19 '17 at 7:48
  • @Philippos I know I didn't come on for the rest of the day – K Split X Oct 19 '17 at 22:23

Try this :

sed -i -r 's/.{10}//' *.java
  • Would I replace file.txt with *.java? – K Split X Oct 18 '17 at 23:50
  • Check my edited post – Gilles Quenot Oct 18 '17 at 23:51
  • When I run this in terminal it actually prints the result to the screen but doesnt actually change the file? – K Split X Oct 18 '17 at 23:52
  • 1
    Which OS are you using ? – Gilles Quenot Oct 18 '17 at 23:54
  • Anyhow, the question asks to cover all .java' files in all subdirectories, so you'll need find` in addition – Philippos Oct 19 '17 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.