FrederickYocum
FrederickYocum

Reputation: 63

How do I alter the n-th line in multiple files using SED?

I have a series of text files that I want to convert to markdown. I want to remove any leading spaces and add a hash sign to the first line in every file. If I run this:

sed -i.bak '1s/ *\(.*\)/\#\1/g' *.md

It alters the first line of the first file and processes them all, leaving the rest of the files unchanged.

What am I missing that will search and replace something on the n-th line of multiple files?

Using bash on OSX 10.7

Upvotes: 4

Views: 937

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 296019

The problem is that sed by default treats any number of files as a single stream, and thus line-number offsets are relative to the start of the first file.

For GNU sed, you can use the -s (--separate) flag to modify this behavior:

sed -s -i.bak '1s/^ */#/' *.md

...or, with non-GNU sed (including the one on Mac OS X), you can loop over the files and invoke once per each:

for f in *.md; do sed -i.bak '1s/^ */#/' "$f"; done

Note that the regex is a bit simplified here -- no need to match parts of the line that you aren't going to change.

Upvotes: 5

user unknown
user unknown

Reputation: 36269

sed -rsi.bak '1s/^/#/;s/^[ \t]+//' *.md

You don't need g(lobally) at the end of the command(s), because you wan't to replace something at the begin of line, and not multiple times.

You use two commands, one to modify line 1 (1s...), seperated from the second command for the leading blanks (and tabs? :=\t) with a semicolon. To remove blanks in the first line, switch the order:

sed -rsi.bak 's/^[ \t]+//;1s/^/#/' *.md

Remove the \t if you don't need it. Then you don't need a group either:

sed -rsi.bak 's/^ +//;1s/^/#/' *.md

-r is a flag to signal special treatment of regular expressions. You don't need to mask the plus in that case.

Upvotes: 0

shawty
shawty

Reputation: 5839

XARgs will do the trick for you:

http://en.wikipedia.org/wiki/Xargs

Remove the *.md from the end of your sed command, then use XArgs to gather your files one at a time and send them to your sed command as a single entity, sorry I don't have time to work it out for you but the wikiPedia article should show you what you need to know.

Upvotes: 0

Related Questions