Home > database >  OSX & SED - Delete all lines after line 25 in a directory of documents
OSX & SED - Delete all lines after line 25 in a directory of documents

Time:10-05

I have a directory that contains thousands of txt files. I need to trim the files so every line after line 25 in each file is deleted. I am using Mac OSX 10.14.6.

How can I do this?


Attempts I have made

After researching I think SED in Mac OSX terminal is the best way to do this.

This page gives examples on how to target lines in SED. So I think the SED command I would need is:

sed '1,25!d'

This tells SED to delete everything apart from lines 1 to 25. When I try it on a single file, it works.

I now need to expand it so it works on a directory of files.

This answer says I can do that using SEDs -n and -i flags (it also mentions an -s flag that doesn't work on OSX).

So I think the code should be like this:

sed -n -i '1,25!d' *.txt

But when I try it, I get this error:

sed: 1: "filename": command a expects \ followed by text

I have tried other variations, but none seem to work.

CodePudding user response:

MacOS uses BSD sed, not GNU sed: read man sed

The -i option requires an argument in BSD sed. If you don't want a backup copy of the file, the argument is an empty string:

$ seq 50 | tee file1 > file2

$ wc file1 file2
 50  50 141 file1
 50  50 141 file2
100 100 282 total

$ sed -i '' -n '1,25p' file1 file2

$ wc file1 file2
 25  25  66 file1
 25  25  66 file2
 50  50 132 total

CodePudding user response:

Better to use q command instead of d for faster execution and pipe it with find xargs like this:

cd some_dir
find . -type f -print0 | xargs -0 -n1 sed -i.bak '25q'
  • Related