I've been trying to delete the second and third lines from about 50 text files.

I need to keep the headers but delete lines "1" and "2", meaning I need to delete the second and third lines of each text file. I have been trying to use:

sed -i.bak '2,3d' *.txt

But in only deletes the lines from the first file in the folder. How can I get this to apply to all the files in the folder?

  • 1
    AFAIK that should have worked since the -i option implies the -s option, meaning that 2,3d should have been applied to each file separately. However if you'd tested it without the -i (and without explicitly adding -s) you would have seen the changes applied only to the first file. – steeldriver Aug 13 '19 at 17:39

Here are two ways, choice depends on how many files you have, how long the names are, and whether or not the filenames have "funny characters.

for i in *.txt ; do
    sed -i.bak '2,3d' "$i"

Or, the complex case:

find . -maxdepth 1 -type f -name '*.txt' -print0 | \
    xargs -0 -r -n 1 sed -i.bak '2,3d'
  • Thank you so much! The first one worked like a charm! – Alexis Dodson Aug 13 '19 at 17:28
  • Then please click the Accept checkmark. – waltinator Aug 13 '19 at 17:51
  • Could you add explanations what these commands do? sed is capable of processing more than one file, so why not just sed -i.bak 2,3d *.txt or find … -exec sed -i.bak 2,3d {} + ? – dessert Aug 13 '19 at 20:31
  • The commands are explained in their man pages. man bash, man sed, man find and man xargs. I see no reason why I should re-document the commands. – waltinator Aug 15 '19 at 13:11

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.