Perl 在每行上更改以捕捉斜线和分隔线

Perl 在每行上更改以捕捉斜线和分隔线,perl,sed,awk,tr,Perl,Sed,Awk,Tr,我有一个txt文件,其中有很多行重复,想改变每一行,其中包含“查找”在最后一个“/”分离,并在它后面添加“-name” Txt文件: 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

我有一个txt文件,其中有很多行重复,想改变每一行,其中包含“查找”在最后一个“/”分离,并在它后面添加“-name”

Txt文件:

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
这应该起作用:

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


修改仅包含
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
添加-i before-wpe以实际更改文件

在更现代的perl版本上:

perl -wpe's!^(find.*/)\K! -name !' file
使用警告;
严格使用;
打开(文件“$ARGV[0]”)#将包含命令的文件作为第一个参数传递
我的@file_contents=;
关闭文件;
#我的@file\u内容=(
#“查找/etc/cron.*”,
#'查找/etc/inet.d/*.conf',
#“查找/etc/rc*”,
#“grep root/etc/passwd”,
#);
#生成命令行
foreach my$行(@file\u contents){
chomp$行;
$line=~s/(.*)(\/.\/)(.*)/$1$2-name$3/if$line=~/find/;
打印“$line\n”;
}

哇,太棒了,我正在考虑在所有字段中循环,等等,但这要好得多。@fedorqui自从OP提到上次的
以来,我认为修改最后一个变量会更好<代码>:)
@jaypal singh这里棘手的部分是捕获唯一的查找,请参见grep上的“添加“-name”。@KalinBorisov事实上,您上面显示的预期输出使我从答案中删除了
/find/
。是否执行
awk'BEGIN{FS=OFS=“/”}/find/{$NF=“-name”$NF}1”文件
仅修改带有
find
的行@Kent哪个徽标?那是我的真名<代码>;)你说的是包含“find”的change行,但是你的例子显示grep行也在变化?
perl -wpe's!^(find.*/)!$1 -name !' file
perl -wpe's!^(find.*/)\K! -name !' file
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";
}