2013-07-23 16 views
0

我有很多行的大多數行重複,想要改變每一行中包含「查找」使最後一個「/」分離和添加後它「-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 
+0

你說含有「發現」變線,但你的例子顯示了grep的行改變嗎? – ysth

回答

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 
+1

這實際上我需要感謝@sudo_O –

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 
+1

哇,輝煌的,我想通過所有領域循環等,但這是更好的方式。 – fedorqui

+0

@fedorqui由於OP提到'last /',我認爲最好修改最後一個變量。 ':)' –

+1

+1不錯。也爲你的漂亮的標誌。 :) – Kent

1
perl -wpe's!^(find.*/)!$1 -name !' file 

添加-i -wpe之前實際更改文件。

在更現代的perl版本:

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

很好的例子謝謝! –

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"; 
}