관심있는 것들 정리

Here Document 본문

utility 사용법/shell

Here Document

내공강화 2014. 7. 21. 00:33

vi에 특정 문자를 입력 후 종료하는 명령을 다음과 같이 here document로 작성가능하다

다음 예제들은 http://tldp.org/LDP/abs/html/here-docs.html 에서 복사한 것이다.

#!/bin/bash

# Noninteractive use of 'vi' to edit a file.
# Emulates 'sed'.

E_BADARGS=85

if [ -z "$1" ]
then
  echo "Usage: `basename $0` filename"
  exit $E_BADARGS
fi

TARGETFILE=$1

Insert 2 lines in file, then save.
#--------Begin here document-----------#
vi $TARGETFILE <<x23LimitStringx23
i
This is line 1 of the example file.
This is line 2 of the example file.
^[
ZZ
x23LimitStringx23
#----------End here document-----------#

# Note that ^[ above is a literal escape
#+ typed by Control-V <Esc>.

# Bram Moolenaar points out that this may not work with 'vim'
#+ because of possible problems with terminal interaction.

exit

또 ex 를 이용한 문자열 치환 스크립트 역시 가능하다.

#!/bin/bash
# Replace all instances of "Smith" with "Jones"
#+ in files with a ".txt" filename suffix. 

ORIGINAL=Smith
REPLACEMENT=Jones

for word in $(fgrep -l $ORIGINAL *.txt)
do
# -------------------------------------
  ex $word <<EOF
  :%s/$ORIGINAL/$REPLACEMENT/g
  :wq
EOF
# :%s is the "ex" substitution command.
# :wq is write-and-quit.
# -------------------------------------
done

Here Document 내에 있는 parameter나 변수가 대치가능하므로 다음과 같은 스크립트도 작성 가능하다.

#!/bin/bash
#Another 'cat' here document, using parameter substitution.

#Try it with no command-line parameters,   ./scriptname
#Try it with one command-line parameter,   ./scriptname Mortimer
#Try it with one two-word quoted command-line parameter,
#                          ./scriptname "Mortimer Jones"

CMDLINEPARAM=1     #  Expect at least command-line parameter.

if [ $# -ge $CMDLINEPARAM ]
then
  NAME=$1          #  If more than one command-line param,
                   #+ then just take the first.
else
  NAME="John Doe"  #  Default, if no command-line parameter.
fi  

RESPONDENT="the author of this fine script"  
  

cat <<Endofmessage

Hello, there, $NAME.
Greetings to you, $NAME, from $RESPONDENT.

#This comment shows up in the output (why?).

Endofmessage

# Note that the blank lines show up in the output.
# So does the comment.

exit


반응형

'utility 사용법 > shell' 카테고리의 다른 글

화면 출력  (0) 2014.07.21