0

我有很多行的 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
4

4 回答 4

4

这应该有效:

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
于 2013-07-23T15:02:49.553 回答
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
于 2013-07-23T15:07:53.073 回答
1
perl -wpe's!^(find.*/)!$1 -name !' file

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

在更现代的 perl 版本上:

perl -wpe's!^(find.*/)\K! -name !' file
于 2013-07-23T15:09:20.857 回答
0
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";
}
于 2013-07-23T15:12:29.603 回答