파일에서 일치하는 줄 뒤에 축어적 bash 변수로 지정된 여러 줄을 추가하시겠습니까?

파일에서 일치하는 줄 뒤에 축어적 bash 변수로 지정된 여러 줄을 추가하시겠습니까?

bash 스크립트의 텍스트 파일에서 일치하는 줄 뒤에 여러 줄을 추가하고 싶습니다. 작업을 위해 어떤 도구를 선택해야 하는지는 특별히 신경 쓰지 않지만 나에게 중요한 것은 스크립트 내부에 "있는 그대로" 추가된 줄을 지정하고 싶다는 것입니다(그래서 해당 도구를 저장할 추가 파일을 생성하지 않고). Bash 변수로 끝나고 그 안에 아무 것도 인용/이스케이프할 필요가 없습니다. 그런 목적으로 '인용된' heredoc을 사용하는 것이 저에게 효과적일 것입니다. 예는 다음과 같습니다 appendtest.sh.

cat > mytestfile.txt <<'EOF'
    "'iceberg'"
    "'ice cliff'"
    "'ice field'"
    "'inlet'"
    "'island'"
    "'islet'"
    "'isthmus'"
EOF

IFS='' read -r -d '' REPLACER <<'EOF'
      "'$oasis$'"
      "'$ocean$'"
      "'$oceanic trench$'"
EOF

echo "$REPLACER"

sed -i "/    \"'ice field'\"/a${REPLACER}" mytestfile.txt

불행히도 이것은 작동하지 않습니다.

$ bash appendtest.sh
      "'$oasis$'"
      "'$ocean$'"
      "'$oceanic trench$'"
sed: -e expression #1, char 39: unknown command: `"'

... sed이스케이프되지 않은 여러 줄 대체가 사용될 때 실패했기 때문입니다. 그래서 내 질문은 다음과 같습니다

  • sed텍스트 줄에서 일치를 수행하고 Bash 변수( $REPLACER예제) 에 지정된 대로 줄을 삽입/추가하는 대신 무엇을 사용할 수 있습니까 ?

답변1

GNU를 사용하는 경우 sed가장 좋은 옵션은 다음 r명령을 사용하는 것입니다.

sed -i "/    \"'ice field'\"/ r /dev/stdin" mytestfile.txt <<'EOF'
      "'$oasis$'"
      "'$ocean$'"
      "'$oceanic trench$'"
EOF

답변2

좋습니다. 다음을 사용하여 편도를 찾았습니다 perl.

cat > mytestfile.txt <<'EOF'
    "'iceberg'"
    "'ice cliff'"
    "'ice field'"
    "'inlet'"
    "'island'"
    "'islet'"
    "'isthmus'"
EOF

IFS='' read -r -d '' REPLACER <<'EOF'
      "'$oasis$'"
      "'$ocean$'"
      "'$oceanic trench$'"
EOF

# echo "$REPLACER"

IFS='' read -r -d '' LOOKFOR <<'EOF'
    "'ice field'"
EOF
export REPLACER # so perl can access it via $ENV
# -pi will replace in-place but not print to stdout; -p will only print to stdout:
perl -pi -e "s/($LOOKFOR)/"'$1$ENV{"REPLACER"}'"/" mytestfile.txt
# also, with export LOOKFOR, this works:
# perl -pi -e 's/($ENV{"LOOKFOR"})/$1$ENV{"REPLACER"}/' mytestfile.txt
cat mytestfile.txt # see if the replacement is done

원하는 대로 출력됩니다.

$ bash appendtest.sh
    "'iceberg'"
    "'ice cliff'"
    "'ice field'"
      "'$oasis$'"
      "'$ocean$'"
      "'$oceanic trench$'"
    "'inlet'"
    "'island'"
    "'islet'"
    "'isthmus'"

관련 정보