mareks
mareks

Reputation: 491

Search and replace with shell script

I need a shell script to find and replace text that would go like:

For each line in a file
  find equation mark "="
  remove everything up to the equation mark on that line and replace it with the string cuts[Counter] where Counter counts how many times such substitutions have been made.

Could anybody help me out with getting started with a script like that?

Upvotes: 1

Views: 466

Answers (3)

Vijay
Vijay

Reputation: 67211

Here is the perl one liner for that:

perl -plne 'if($.==1){$count=1}if(/=/){$_=~s/[^\=]*[=]/cut[$count]/g;$count++}' temp

Upvotes: 0

cmh
cmh

Reputation: 10927

In pure bash:

counts=0
while IFS= read -r line; do
    if [[ "$line" =~ "=" ]]; then
        echo "${counts}${line#*=}"
        counts=$((counts+1))
    fi
done <infile

Note that this will exclude the '='. You can reinclude it in the ehco statement if necessary.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203219

Assuming you mean "up to the first equation mark..." and you want to keep the =, this should do it:

awk '{c += sub(/[^=]+=/,"cuts["c+0"]=") }1' file

Upvotes: 5

Related Questions