Delete first 10 characters of every line in textfile

5,206

Solution 1

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.

Solution 2

Try this :

sed -i -r 's/.{10}//' *.java
Share:
5,206

Related videos on Youtube

K Split X
Author by

K Split X

Updated on September 18, 2022

Comments

  • K Split X
    K Split X over 1 year

    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
    
    etc
    

    NOT THIS:

              package com.a;
              import java.util.List
    
              etc
    

    Thank you

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

    • Philippos
      Philippos over 6 years
      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.
    • K Split X
      K Split X over 6 years
      @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
    K Split X over 6 years
    Would I replace file.txt with *.java?
  • Gilles Quenot
    Gilles Quenot over 6 years
    Check my edited post
  • K Split X
    K Split X over 6 years
    When I run this in terminal it actually prints the result to the screen but doesnt actually change the file?
  • Gilles Quenot
    Gilles Quenot over 6 years
    Which OS are you using ?
  • Philippos
    Philippos over 6 years
    @KSplitX In this case you are supposed to mark the helpful answer as solution, so future readers will know which answer worked.
  • K Split X
    K Split X over 6 years
    @Philippos I know I didn't come on for the rest of the day
  • Weekend
    Weekend about 3 years
    -r instead of escape 🎉