Search code examples
linuxbashawksedscripting

How to process a file and replace a pattern with the line number


So, I'm trying to design a little program and I'm planning to use a config file and have the ID be the line number. Here's a small example .conf file:

ID=_PATTERN_ 
STATE=window 
DIR=_code 
GEO=1200x250+0+32 
CMDS=cd home

I'm trying to find a way to replace _PATTERN_ with the line number. This is mainly because the ID isn't important to the person creating the file, just for the processing script that uses the .conf. So I figured, just make the ID autogenerated through some preprocessing. I was thinking of using sed or awk but I'm not really sure what to look up to get the answer to this.


Solution

  • At the shell prompt:

    $ awk '{ gsub(/_PATTERN_/, FNR); print }'
    _PATTERN_
    1
    _PATTERN_ _PATTERN_
    2 2
    foo _PATTERN_
    foo 3