sed script - transform 1st matching line only

How do transform only the first line that matches my regex? I've tried q but it just quit my script in the middle.

For transforming the line in sed,you can use substitute command.For changing the first line alone.You use the following command.

sed -r '1s/^[0-9]+$/Numerical Values/' <filename>

The above command will change the first line into numerical values if it contains the numbers in the first line.

Generally the sed command's substitution with the given pattern will replace the first occurrence of the match unless we explicitly specified the g flag.

Yeah thillai,in substitute command if we didn't specify global flag,then it will replace only the first occurrence.But,I don't know why you have given this answer here?Did you read the question?Otherwise,you're saying in my solution,we need to give g flag?

Well, I think the original question asked was to be able to replace only the FIRST macth of the reg expression and not necessarily the first line, which means, it can be match anywhere in the file but replace only the first occurance only..Confirmations?

Thanks for the responses guys!

Yes, my question is the 1st regex match anywhere in the file. Not the 1st line of the file. I'm trying to do something like this:

/regex/ {
              transform only the first matching line
}

do some other stuff

Try this:

awk 'BEGIN{cnt=0}$0 ~ /regexpr/ && cnt == 0{gsub(/regexpr/,"ReplacementString");cnt++}1' filename

cheers,
Devaraj Takhellambam

 awk '/regex/ && a=="" {print $0 ; a++}'  urfile
 awk '/regex/ {print $0 ; exit}'  urfile

I'm sorry for my lack of knowledge but I am trying to do this inside of a sed script with many steps. I've looked into awk but awk doesn't seem to do some of the other things that I want to do.

Is it not possible to do in sed?

or is there an easy way to combine awk commands with sed commands in a multi-line file that is easy to run?

You can always pass the o/p of the awk script to the sed script. if you really need to use sed, then you may need to explore loops in sed.

---------- Post updated at 03:12 AM ---------- Previous update was at 03:00 AM ----------

Or simply,

sed '0,/regexp/{s/regexp/ReplaceString/}' filename

cheers,
Devaraj Takhellambam