4

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?

1 Answer 1

4

You could use...

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

Explanation:

  • -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...

2
  • +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 ;) Commented Sep 28, 2016 at 12:12
  • @steeldriver lol facepalm
    – Zanna
    Commented Sep 28, 2016 at 12:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .