IT

### 리눅스에서 문자 변환을 할때 sed 명령어를 주로 사용한다.

Dream Come True 2020. 12. 10. 21:41
반응형
변환

sed 's/|//g' access.log > access1.log  
:  access.log 파일에서 "|" 해당 문자를 "" 공백으로 변환하여, access1.log 파일로 저장한다.

sed 's/GET/"GET/g'  
: GET 문자열을 "GET 로 변환


삭제

sed '/blue/d' test.txt    
: test.txt 파일에서 blue 문자가 포함된 줄을 삭제 하여 출력한다.

sed '/img/!d' test.txt      
: img 문자가 있는 줄만 지우지 않는다.

sed '1,2d' test.txt      
: 처음 1줄, 2줄을 지운다

sed '^$/d test.txt       
: 공백라인을 삭제한다.

 

##### sed 명령을 여러개 할 경우 -e 옵셥으로 여러게 하면 된다.

sed -e " -e " -e "

# 텍스트 가운데로 옮기기
sed -e :a -e 's/^.\{1,77\}$/ & /;ta' # method 1
sed -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' # method 2

# substitute (find and replace) "foo" with "bar" on each line
# foo 를 bar로 교체
# 첫번째 매치를 교체
sed 's/foo/bar/' # replaces only 1st instance in a line
# 네번째 매치를 교체
sed 's/foo/bar/4' # replaces only 4th instance in a line
# 모든 매치를 교체
sed 's/foo/bar/g' # replaces ALL instances in a line
sed 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
sed 's/\(.*\)foo/\1bar/' # replace only the last case
# baz 가 있는 줄만 foo를 bar 로 교체
sed '/baz/s/foo/bar/g'
# baz가 없는 줄만 foo를 bar 로 교체
sed '/baz/!s/foo/bar/g'
# 다섯 줄마다 빈줄 더하기
gsed '0~5G' # GNU sed only
sed 'n;n;n;n;G;' # other seds

#윈도우에서 유닉스 포맷을 윈도우 포맷으로 교환
sed "s/$//" # method 1
sed -n p # method 2


# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format.
# 유닉스 포맷을 윈도우 포맷으로 교환
sed "s/$/`echo -e \\\r`/" # command line under ksh
sed 's/$'"/`echo \\\r`/" # command line under bash
sed "s/$/`echo \\\r`/" # command line under zsh
sed 's/$/\r/' # gsed 3.02.80 or higher


FILE SPACING:
파일 빈공간 붙이기

# double space a file
# 두줄 만들기
sed G

# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.

sed '/^$/d;G'

# triple space a file
# 세줄 만들기
sed 'G;G'

# undo double-spacing (assumes even-numbered lines are always blank)
# 두줄 만들기 취소
sed 'n;d'

# insert a blank line above every line which matches "regex"
# 매치된 정규식 표현위에 빈줄 넣기
sed '/regex/{x;p;x;}'

# insert a blank line below every line which matches "regex"
# 매치된 정규식 표현밑에 빈줄 넣기
sed '/regex/G'

# insert a blank line above and below every line which matches "regex"
# 매치된 정규식 표현 위,아래로 빈줄 넣기
sed '/regex/{x;p;x;G;}'

반응형