0

I have this script to remove the first 4 lines of every file in a folder if their extension is .txt.

I want to be able to place a file.command with this script in the same folder so I can just double click on it and execute it.

So I made a file with this:

#!/bin/bash

find . -type f -name "*.txt" -exec sed -i.bak '1,4d' {} \;

If I run the file I have all of my Mac txt files 4 lines removed :(

I thought the find . was meant to stay in the same folder ...

How do I fix it in order to have the command run ONLY in the folder the file.command is?

  • Mine works well try to run it with -maxdepth 1 and remove the sed part to see the files that will be affected – George Udosen Sep 20 '17 at 11:01
  • Are you running it from the folder in question? – George Udosen Sep 20 '17 at 11:04
  • I made the file in the same folder I have the txts and I double click on it - yes same folder – Mr.Web Sep 20 '17 at 11:06
  • Run with -maxdepth 1 and see what happens – George Udosen Sep 20 '17 at 11:08
  • I tried find . -maxdepth 1 -type f -name "*.txt" -exec sed -i.bak '1,4d' {} \;but nothing happens.. – Mr.Web Sep 20 '17 at 13:07
1

This code:

find . -maxdepth 1 -type f -name "*.txt" -exec sed -i.bak '1,4d' {} \;

actually works, the issue were:

  1. The created file with the command wasn't made executable for that do:

    chmod +x file.command
    
  2. Then run the command from the terminal with:

    ./file.command
    
0

As has been commented, find descends into subdirectories by default.

Do this instead:

#!/bin/bash
cd "$(dirname "$0")"          # change directory to the location of the script
for file in *.txt; do         # and iterate over the .txt files
    sed -i.bak '1,4d' "$file"
done

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.