How to find/replace and increment a matched number with sed/awk?

后端 未结 4 946
情书的邮戳
情书的邮戳 2020-11-30 01:53

Straight to the point, I\'m wondering how to use grep/find/sed/awk to match a certain string (that ends with a number) and increment that number by 1. The closest I\'ve come

4条回答
  •  自闭症患者
    2020-11-30 02:31

    This perl command will search all files in current directory (without traverse it, you will need File::Find module or similar for that more complex task) and will increment the number of a line that matches cache_version=. It uses the /e flag of the regular expression that evaluates the replacement part.

    perl -i.bak -lpe 'BEGIN { sub inc { my ($num) = @_; ++$num } } s/(cache_version=)(\d+)/$1 . (inc($2))/eg' *
    

    I tested it with file in current directory with following data:

    hello
    cache_version=3
    bye
    

    It backups original file (ls -1):

    file
    file.bak
    

    And file now with:

    hello
    cache_version=4
    bye
    

    I hope it can be useful for what you are looking for.


    UPDATE to use File::Find for traversing directories. It accepts * as argument but will discard them with those found with File::Find. The directory to begin the search is the current of execution of the script. It is hardcoded in the line find( \&wanted, "." ).

    perl -MFile::Find -i.bak -lpe '
    
        BEGIN { 
            sub inc { 
                my ($num) = @_; 
                ++$num 
            }
    
            sub wanted {
                if ( -f && ! -l ) {  
                    push @ARGV, $File::Find::name;
                }
            }
    
            @ARGV = ();
            find( \&wanted, "." );
        }
    
        s/(cache_version=)(\d+)/$1 . (inc($2))/eg
    
    ' *
    

提交回复
热议问题