【问题标题】:Change on every line to catch slash and separate更改每一行以捕获斜线并分隔
【发布时间】:2013-07-22 17:37:56
【问题描述】:

我有很多行的 txt 文件,其中大部分重复,想要更改包含“find”的每一行,在最后一个“/”上进行分隔并在其后添加“-name”。

文本文件:

find /etc/cron.*
find /etc/inet.d/*.conf
find /etc/rc*
grep root /etc/passwd

预期视图:

find /etc/ -name cron.*
find /etc/inet.d/ -name *.conf
find /etc/ -name rc*
grep root /etc/passwd

【问题讨论】:

  • 您说更改包含“find”的行,但您的示例显示 grep 行也在更改?

标签: perl sed awk tr


【解决方案1】:

这应该有效:

awk 'BEGIN{FS=OFS="/"}{$NF=" -name "$NF}1' file

$ cat file
find /etc/cron.*
find /etc/inet.d/*.conf
find /etc/rc*
grep root /etc/passwd

$ awk 'BEGIN{FS=OFS="/"}{$NF=" -name "$NF}1' file
find /etc/ -name cron.*
find /etc/inet.d/ -name *.conf
find /etc/ -name rc*
grep root /etc/ -name passwd

【讨论】:

  • 哇,太棒了,我正在考虑循环遍历所有领域等,但这要好得多。
  • @fedorqui 既然 OP 提到了last /,我认为只修改最后一个变量会更好。 :)
  • @jaypal singh 这里的棘手部分是只捕获 find,在 grep 上查看也是添加“-name”。
  • @KalinBorisov 实际上,您上面显示的预期输出使我从答案中删除了/find/。执行awk 'BEGIN{FS=OFS="/"}/find/{$NF=" -name "$NF}1' file 仅修改带有find 的行。
  • @Kent 哪个标志?那是我的真名! ;)
【解决方案2】:

仅修改包含find 的每一行:

$ awk '/^find /{$NF=" -name "$NF}1' FS='/' OFS='/' file
find /etc/ -name cron.*
find /etc/inet.d/ -name *.conf
find /etc/ -name rc*
grep root /etc/passwd

【讨论】:

    【解决方案3】:
    perl -wpe's!^(find.*/)!$1 -name !' file
    

    在 -wpe 之前添加 -i 以实际更改文件。

    关于更现代的 perl 版本:

    perl -wpe's!^(find.*/)\K! -name !' file
    

    【讨论】:

      【解决方案4】:
      use warnings;
      use strict;
      
      open (FILE, "$ARGV[0]"); #pass file containing commands as first argument
      my @file_contents = <FILE>;
      close FILE;
      
      #my @file_contents = (
      #   'find /etc/cron.*',
      #   'find /etc/inet.d/*.conf',
      #   'find /etc/rc*',
      #   'grep root /etc/passwd',
      #);
      
      #Build command line
      foreach my $line (@file_contents){
          chomp $line;
          $line =~ s/(.*?) (\/.*\/)(.*)/$1 $2 -name $3/ if $line =~ /find/;
          print "$line\n";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-05
        • 2020-10-01
        • 2014-07-03
        相关资源
        最近更新 更多