2012-10-22 3 views
1
$ cat file1 
"rome" newyork 
"rome" 
rome 

빈 칸을 채우려면 무엇이 필요합니까?큰 따옴표 사이에있는 문자열을 제외한 모든 문자를 "hello"로 바꾸십시오.

$ sed ____________________ file1 

나는

"rome" newyork 
"rome" 
hello 

같은 출력 내가이없는 인사를 변경하려는 경우 내 입력이

$ cat file1 
/temp/hello/ram 
hello 
/hello/temp/ram 

같은 경우는 어떻게해야합니까 슬래시 싶어?

temp/hello/ram 
happy 
/hello/temp/ram 

답변

0
sed 's/[^\"]rome[^\"]/hello/g' your_file 

아래 시험 :

두 번째 문제는 (라인 당 하나 개의 헬로 가정) 간단한 펄 한 라이너를 해결할 수
> cat temp 
    "rome" newyork 
    "rome" 
    rome 

> sed 's/[^\"]rome[^\"]/hello/g' temp 
    "rome" newyork 
    "rome" 
    hello 

> 
+0

Thaknks. 내가 이것을 찾고 있는데 : –

+0

입력이 "/ temp/hello/ram hello/hello/temp/ram"과 같은 경우, 내가 할 일을 슬래시가 없으면 안부를 변경하고 싶다면 ??? 샘플 O/P : temp/hello/ram happy/hello/temp/ram [안녕하세요 행복하게 변경]. –

0

romehello로 변경 (행복 인사 변경)하지만 newyork 아닌가요? 질문을 올바르게 읽는다면, 큰 따옴표로 묶지 않은 것을 모두 hello으로 바꾸려고하십니까? (? 입력 문자열 "" 어떻게되는지)

당신이 원하는 정확한 사용 사례에 따라, 당신은 아마 이런 식으로 뭔가를 원하는 :

sed 's/\".*\"/hello/' 
0

내가 그 동봉 제외한 모든 다른 사람을 대체 할 수있는 직접적인 방법을 참조 해달라고 내부 ""

그러나 재귀 적 sed를 사용하면 무차별 대입 방식을 사용하여 달성 할 수 있습니다.

cat file1 | sed "s/\"rome\"/\"italy\"/g" | sed "s/rome/hello/g" | sed "s/\"italy\"/\"rome\"/g"

+0

그러나, 나는 하나의 sed가있는 간단한 명령을보고 싶습니다. – Baskar

0

:

perl -pe 'next if /\//; s/hello/happy/;' 

첫 번째 문제는 문자열 내부에 있는지 추적하기 위해 내부 책을 보관해야합니다. 아닙니다. 이것은 perl로도 해결할 수 있습니다 :

#!/usr/bin/perl -w 
use strict; 
use warnings; 

my $state_outside_string = 0; 
my $state_inside_string = 1; 

my $state = $state_outside_string; 

while (my $line = <>) { 
    my @chars = split(//,$line); 
    my $not_yet_printed = ""; 
    foreach my $char (@chars) { 
     if ($char eq '"') { 
      if ($state == $state_outside_string) { 
       $state = $state_inside_string; 
       $not_yet_printed =~ s/rome/hello/; 
       print $not_yet_printed; 
       $not_yet_printed = ""; 
      } else { 
       $state = $state_outside_string; 
      } 
      print $char; 
      next; 
     } 
     if ($state == $state_inside_string) { 
      print $char; 
     } else { 
      $not_yet_printed .= $char; 
     } 
    } 
    $not_yet_printed =~ s/rome/hello/; 
    print $not_yet_printed; 
} 
관련 문제