I have


I would like


where 123 will change between the files I'd like to run this on.

I can get param2 using sed -i "s/param1=\([0-9]\+\)/param2='\1'/g" '{}' \; But then I will lose param1.

I can also append line param2 using sed -i "param1='\([0-9]\+\)';/a \param2=\1; but the pattern isn't recognised and i end up with param2=1

Is there a way to combine these two commands, or another way of working this?

Many thanks!


You can capture the entire match as well as the number group and then specify both in the output:

echo "param1='123'" | sed "s/\(param1='\([0-9]\+\)'\)/\1\nparam2=\2/g"
  • Perfect, thank you. Are you outputting the entire match, then adding a newline with nparam2 and then outputting the second match? Or how does this work? – user1792403 Dec 19 '13 at 13:24
  • 2
    @user1792403: Yes, that is it. Please note that \1 can be replaced by & (entire matched string) and the outer \( and \) can be removed. --- Also the g flag at the end is superfluous as the substitution will most probably not work with multiple matches on a single line as wanted. --- Please not that not all implementations of sed support \n for inserting newline. GNU sed supports it. – pabouk Dec 19 '13 at 13:45
  • When i have enough reputation points I will come back to +1 this comment, thank you for the information. – user1792403 Dec 19 '13 at 14:05

Here are some more options:

  1. Perl

    echo "param1='123'" | perl -lpe 'print; s/(.+=).(\d+)./$1$2/'
  2. awk

    echo "param1='123'" | awk -F"[ =']" '{print $0"\n"$1"="$3}'
  3. shell

    echo "param1='123'" | while read l; do echo "$l"; echo "${l//\'/}"; done
  4. A simpler sed

    echo "param1='123'" | sed "p;s/'//g"
  • Nice answer! I’m just wondering why the tool chosen by OP (sed) is listed as the last one. Moreover when its command is the simplest and shortest one… – Melebius Nov 30 '17 at 9:16
  • @Melebius because when I posted this there was already another sed answer, so I gave other choices. Also, while the sed is the shortest, it is also the mot cryptic. – terdon Nov 30 '17 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.