【问题标题】:file manipulation : shell script find and increment文件操作:shell脚本查找和递增
【发布时间】:2010-02-08 22:51:08
【问题描述】:
 #something here
 port 4444

 #something here

 port 4444

所以我有上面这样的文件,我会找到带有单词“port”的行并将其旁边的数字(数字可以是任何数字 - 不必固定为 4444)加 1。

例如,结果文件的格式应该是

 #something here
 port 4444

 #something here

 port 4445

任何想法,我认为我们需要使用 sed ,但不确定是否要增加它。

编辑: 再次抱歉,我以为我会根据 sed 得到答案,所以没有考虑职位。这是确切的文件内容

$cat file
data dev-1
type client
option type tcp
option host 99.160.131.163
option nodelay on
option port 6996
end

data dev-2
type client
option type tcp
option host 99.160.131.164
option nodelay on
option port 6996
end

我想更改端口号并增加它。不便之处再次抱歉。

【问题讨论】:

  • 对不起,我改了标题,让我的问题更清楚。我需要在文件中编辑这些值。

标签: linux shell scripting


【解决方案1】:
$ awk 'f && $2=="port"{ $NF=num} $2=="port"{ num=$NF+1; f=1 } 1 ' file
data dev-1
type client
option type tcp
option host 99.160.131.163
option nodelay on
option port 6996
end

data dev-2
type client
option type tcp
option host 99.160.131.164
option nodelay on
option port 6997
end

【讨论】:

    【解决方案2】:
    port=444
    ((port+=1))
    echo $port
    

    参考The Double-Parentheses Construct

    【讨论】:

    • 另外:((port++)),但您的回答并未解决 OP 的问题。
    【解决方案3】:

    我会使用awk:

    awk '
        BEGIN{p=-1}
        { if($2=="port"){if(p==-1){p=$3}else{p++};print $1,$2,p} else {print} }' file
    

    【讨论】:

      【解决方案4】:

      Perl 脚本将是:

      $ perl -pe 'if (/^(port )(\d+)/) { $_ = "$1" . ($2+$count) . "\n" if $count; $count++; }' < aaa.txt
      #something here
      port 4444
      
      #something here
      
      
      port 4445
      port 4446
      

      输入数据:

      $ cat aaa.txt
      #something here
      port 4444
      
      #something here
      
      
      port 4444
      port 4444
      

      【讨论】:

        猜你喜欢
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 2011-07-06
        • 1970-01-01
        • 2023-04-05
        • 2016-12-04
        • 1970-01-01
        • 2014-05-23
        相关资源
        最近更新 更多