터미널/Bash 스크립트를 사용하여 디렉터리의 모든 파일에 문자열을 삽입하는 방법

터미널/Bash 스크립트를 사용하여 디렉터리의 모든 파일에 문자열을 삽입하는 방법

파일이 잔뜩 있어요.

AcademicCapIcon.svelte        ArrowSmLeftIcon.svelte        CalculatorIcon.svelte
AdjustmentsIcon.svelte        ArrowSmRightIcon.svelte       CalendarIcon.svelte
...
...

모든 파일의 형식은 동일합니다. 예를 들어 AcademicCapIcon.svelte다음과 같은 것이 있습니다.

<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
  <path d="M12 14l9-5-9-5-9 5 9 5z"/>
  <path d="M12 14l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14z"/>
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 14l9-5-9-5-9 5 9 5zm0 0l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14zm-4 6v-7.5l4-2.222"/>
</svg>

각 파일의 시작 부분에 다음 내용을 삽입하고 싶습니다.

<script>
  export let className = "h-6 w-6";
</script>


class={className}뒤에 삽입되었습니다 xmlns="http://www.w3.org/2000/svg".

예를 들어 위 파일의 최종 결과 AcademicCapIcon.svelte는 다음과 같습니다.

<script>
  export let className = "h-6 w-6";
</script>

<svg xmlns="http://www.w3.org/2000/svg" class={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
  <path d="M12 14l9-5-9-5-9 5 9 5z"/>
  <path d="M12 14l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14z"/>
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 14l9-5-9-5-9 5 9 5zm0 0l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14zm-4 6v-7.5l4-2.222"/>
</svg>

터미널이나 Bash 스크립트를 사용하여 이 작업을 어떻게 수행합니까?

답변1

작은 스크립트를 사용하여 *.svelte 파일을 반복하고 각 파일에 sed를 적용할 수 있습니다.

for FILE in *.svelte; do
  sed -e '1i<script>\n  export let className = "h-6 w-6";\n</script>\n' -e 's/svg" fill/svg" class={className} fill/' $FILE >$FILE.new
done

출력 파일은 .new 확장자를 가진 원래 파일 이름이 되지만, 충분히 용감하다면 sed 명령에 -i 옵션을 추가하고 끝에서 >$FILE.new를 제거하십시오.

답변2

삽입물을 자체 파일에 넣고 시도해보십시오.

sed 's|xmlns="http://www.w3.org/2000/svg"|& class={className}| ' insert_file orig_file
<script>
  export let className = "h-6 w-6";
</script>
<svg xmlns="http://www.w3.org/2000/svg" class={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
.
.
.
</svg>

관련 정보