2016-09-17 2 views
1

을 일치 포함하지 않는 모든 라인 교체 :나는이 모양이 데이터 파일을 일하고 있어요 문자열

text in file 
hello random text in file 
example text in file 
words in file hello 
more words in file 
hello text in file can be 
more text in file 

내가 하지이 문자열을 포함하는 모든 라인을 대체하기 위해 노력하고있어를 hellomatch에 나오지도 사용하므로 출력은 다음과 같습니다

match 
hello random text in file 
match 
words in file hello 
match 
hello text in file can be 
match 

내가 sed '/hello/!d'를 사용하여 시도하지만 그 라인을 삭제합니다. 또한, 나는 sed에서 !을 사용하여 일치시킬 수 있다고 읽었지 만 모든 라인을 일치시키고 올바르게 대체하는 방법을 모르겠습니다. 네가 어떤 방향으로 나에게 줄 수 있다면 정말 고마워.

답변

3

당신은 이런 식으로 작업을 수행 할 수 있습니다

$ sed '/hello/!s/.*/match/' infile 
match 
hello random text in file 
match 
words in file hello 
match 
hello text in file can be 
match 

/hello/! 우리가 hello을 포함하지 않는 선에서만 대체하고 확인합니다 (.*) (당신은 그 권리를했다), 그리고 대체는 전체 패턴 공간을 대체 match.

+0

완벽하게 작동합니다. 도와 줘서 고마워. 이것은 의미가 있습니다. 잠시 시간을 내 시어 upvote하십시오. – DomainsFeatured

6

awk the rescue!

$ awk '!/hello/{$0="match"}1' file 

"hello"와 일치하지 않는 행을 "match"로 바꾸고 모든 행을 인쇄하십시오.

+0

헤이 Karakfa, 이것은 좋은 그러나 또한 다른 라인을 제거하다 라인 교체. – DomainsFeatured

+0

모든 행을 인쇄하려면'1'이 있어야합니다. – karakfa

+0

아, 맞습니다. 고맙습니다. 나는 awk에 너무 좋지 않다. 그러나 이것은 크다. – DomainsFeatured

0

는 그냥 c (변경) 명령을 사용하여 명확성, 단순성 등 : 대한

awk '{print (/hello/ ? $0 : "match")}' file 
3

Sed의를 AWK를 사용

$ sed '/hello/!c match' file 
match 
hello random text in file 
match 
words in file hello 
match 
hello text in file can be 
match 
관련 문제