How can I find a specific file and then delete some lines from it using terminal in a single line?

e.g. I want to find file.txt in my some specific directory and then I want to delete lines from 5 to 10 within it. Is it possible to do it using a single line command?


You could use...

find /path/to/specific/directory -maxdepth 1 -type f -name "file.txt" -exec sed -i.bak '5,10 d' '{}' \;


  • -maxdepth 1 don't look in any subdirectories of the specified directory
  • -type f only find files, not directories
  • -exec do the following command to the found files
  • sed '5,10 d' delete lines from 5 to 10
  • -i.bak modify the file itself rather than printing to stdout but make a backup copy of the original file with the extension .bak

EDIT: although actually if you know exactly where the file is and what it's called you can obviously do

sed -i.bak '5,10 d' /path/to/file.txt

silly me...

  • +1 ... although if you know it's called file.txt and that it's at -maxdepth 1 in /path/to/specific/directory ... you don't really need to find it ;) – steeldriver Sep 28 '16 at 12:12
  • @steeldriver lol facepalm – Zanna Sep 28 '16 at 12:13

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.