使用shell脚本进行搜索和替换

时间:2012-11-22 16:56:05

标签: bash shell sed awk

我需要一个shell脚本来查找和替换类似的文本:

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.

有没有人可以帮助我开始使用这样的脚本?

3 个答案:

答案 0 :(得分:5)

假设你的意思是“直到第一个等式标记......”并且你想保留=,这应该这样做:

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

答案 1 :(得分:1)

纯粹的bash:

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

请注意,这将排除'='。如有必要,您可以将其重新包含在ehco声明中。

答案 2 :(得分:0)

这是perl one liner:

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