4
Consider I have the following file:
echo "1
2
3
4
1
2
3
4
1
2
3
4
1
2
3
4
" > ztest
Here I'd like to change only the first 1
into 5
and leave everything else intact.
I know sed
has a quit
command - so I'm trying the following:
$ sed 's/1/{5;q}/' ztest
{5;q}
2
3
4
{5;q}
2
3
4
{5;q}
2
3
4
{5;q}
2
3
4
This changes all lines, so it's no good. So, then I try this:
$ sed '{s/1/5/;q}' ztest
5
Now, this apparently does as requested - changes the first line and exits; however, I'd like the rest of the lines intact! (since this, basically has the effect of replacing the entire file with a single '5')
So I'm at a loss at what kind of syntax is needed? Note that I need this to change an "early" line in a gigabyte file inline (using sed -i
); thus I'd like sed
to only search and replace in the first brief section - and after that, output lines unchanged (since sed -i
anyways dumps into a temp file first, and then overwrites the original); hoping to save some processing time.
Thanks in advance for any answers,
Cheers!
EDIT: forgot subquestion: is it possible to extend this to first n matches? (say, in the file above, first two '1's are changed to 5 - rest of it is output verbatim?)
Are you stuck with
sed
only? – Mat – 2012-02-26T18:43:59.043HI @Mat - not really; just the first one I resort to when I have t replace inline in text files - any other suggestions are welcome! – sdaau – 2012-02-26T18:46:14.617
1
same situation here
– None – 2012-02-26T19:11:00.297Many thanks for that link, @selman - I like the trick with line 0 (as in
0,/Apple/{s/Apple/Banana/}
) from there - cheers! – sdaau – 2012-02-26T19:58:22.107