Question: I have got around 50 big text files (~4GB) and I only need to replace one string situated in the first 100 lines of these files. In fact what I would need is an unix command line that look for the first match, replace it in place and break.

I've tried playing with sed but I'm still struggling to get a satisfying result.

Answer: 
You can edit up to the first match using `sed`:

```
sed -e '1,/pattern/{s/pattern/replace/;}'

```

On lines 1 to N-1 (where line N contains the pattern), the substitution does nothing; on line N, it does the real work. Thereafter, you're no longer in the `1,/pattern/` range of lines so there is no further transformation.

Note that this doesn't work if line 1 matches the pattern; it then makes changes in line 1 and the next line that matches the pattern. With GNU `sed` at least, you can change the `1` to `0` and that works OK.

```
printf "%s\n" pattern pattern pattern pattern |
sed -e '0,/pattern/{s/pattern/replace/;}'

```

However, the description says "in the first 100 lines" and while line 1 is in the first 100 lines, that isn't the way you'd normally describe it when it appears on line 1.

You can add a `-i` option to overwrite the original file once you've tested it. Beware: not all versions of `sed` support `-i` and on Mac OS X, the backup suffix is mandatory `-i.bak` (but can be empty: use `-i ''`). By contrast, GNU `sed` has an optional suffix which must be attached to the `-i` option. Hence, `-i.bak` works with both GNU and Mac (BSD) `sed`; other uses of the `-i` option are specific to the variant of `sed` you're using.
```
sed -i '1,100 { :a; N; $! ba; s/input/output/ }' file

```

* `:a; N; $! ba` is appending first 100 lines in pattern space
* all 100 lines will be treated like one string.
* Then substitution will take care only on first matched pattern.
* `-i` is inplace editing

`q` can't be used after replacement since it will stop printing the rest of the lines.

Also before executing above sed i'll recommend checking is pattern string inside file and where with 

```
sed -n '/patternstring/{=;p}' file

```

where = is printing line number (some grep styled sed command) 

or if you want to quit imidiatelly after finding first match 

```
sed -n '/patternstring/{=;p;q}' file

```