How many copies have impacted the team?

Is there a way to use it sed

from the cli to return the number of lines, or better yet, how many instances were affected by the command that can have multiple effects on the line if a global parameter is used? This would pretty much mean to me how many substitutions were done.

I think it would be possible to dump to a new file and then run diff

in two files later, but I need to know how many instances are affecting a command, not so good. I was just wondering if there might be a function native sed

that can be used.

+3


source to share


2 answers


As far as I know, sed does not have a built-in function for manipulating variables (like incrementing an internal counter). Definitely one of the functions that awk called that sed was missing . So I would advise you to switch to awk and then you can easily use an awk script like:



BEGIN { counter = 0 }
/mypattern/ { do-whatever-you-want; counter++ }
END { print counter }

      

+5


source


You are asking for a solution sed

. Here's a clean approach sed

that does some of what you want:

sed 's/old/new/;t change;b;:change w changes'

      

After doing this, the modified lines, if any, are written to the file changes

.

How it works:

  • s/old/new/;

    Replace this with whatever replacement you want to do.

  • t change;

    This says sed

    to jump to the label change

    if the previous command s

    made any changes.

  • b;

    If the previous jump failed, this command is executed b

    , which ends the processing of this line.

  • :change w changes

    This tells sed

    to write the current line changed by your command s

    to a file changes

    .



Next step

The next step here is to count the changes. To this end, he sed

can perform arithmetic
, but this is not for the faint of heart.

OSX

As far as I remember, sed

the Mac OSX version does not support chaining commands along with semicolons. Try this instead:

sed -e 's/old/new/' -e 't change' -e b -e ':change w changes'

      

+2


source







All Articles