bestsource

전체 디렉터리 트리에 대한 줄 끝 부분 변환(Git)

bestsource 2023. 7. 18. 21:50
반응형

전체 디렉터리 트리에 대한 줄 끝 부분 변환(Git)

다음 상황:

저는 OS X를 실행하는 Mac에서 일하고 있으며 최근에 회원들이 모두 Windows를 사용하는 프로젝트에 참여했습니다.저의 첫 번째 작업 중 하나는 Git 저장소에 코드베이스를 설정하는 것이었기 때문에 FTP에서 디렉터리 트리를 가져와서 로컬로 준비한 Gitrepo에 체크인하려고 했습니다.이 일을 하려고 할 때, 제가 얻은 것은 이것뿐이었습니다.

fatal: CRLF would be replaced by LF in blog/license.txt.

이것은 "블로그" 폴더 아래의 모든 파일에 영향을 미치기 때문에 트리의 모든 파일을 유닉스 줄바꿈으로 편리하게 변환하는 방법을 찾고 있습니다.바로 사용할 수 있는 툴이 있습니까? 아니면 직접 스크립트를 작성할 수 있습니까?

참고로, 라인 엔드와 관련된 my Git 구성:

core.safecrlf=true
core.autocrlf=input

도스2는 당신을 위해 그렇게 합니다.상당히 간단한 프로세스입니다.
dos2unix filename

툴베어 덕분에 줄 끝을 재귀적으로 대체하고 공백, 따옴표 및 셸 메타 문자를 적절하게 처리하는 원라이너가 있습니다.

find . -type f -exec dos2unix {} \;

dos2unix 6.0 이진 파일을 사용하는 경우 무시됩니다.

GNU가 합니다.grep그리고.perl이렇게 하면 CRLF가 현재 디렉터리 아래의 이진이 아닌 파일에서 LF로 재귀적으로 변환됩니다.

find . -type f -exec grep -qIP '\r\n' {} ';' -exec perl -pi -e 's/\r\n/\n/g' {} '+'

작동 방식

; 현재디리에으로찾기적재, 변경서토귀를 합니다..blog또는whatev교체를 제한하는 하위 디렉터리:

find .

일반 파일만 일치:

  -type f

파일에 CRLF가 포함되어 있는지 테스트합니다.이진 파일을 제외합니다. »grep모든 일반 파일에 대한 명령입니다.바이너리를 제외한 가격입니다.오래된 것이 있다면,grep당신은 그것을 이용하여 테스트를 만들어 볼 수 있습니다.file명령:

  -exec grep -qIP '\r\n' {} ';'

CRLF를 LF로 교체합니다.'+' 번째로-exec말한다find일치하는 파일을 축적하여 명령의 호출 중 하나(또는 가능한 한 적게)에 전달합니다. 예를 들어 파이프를 사용하여xargs파일 경로에 공백, 따옴표 또는 기타 셸 메타 문자가 포함되어 있으면 문제가 없습니다.i-piPerl에 파일을 수정하도록 지시합니다.사용할 수 있습니다.sed또는awk여기서 작업을 수행하면 '+'를 ';'로 변경하고 각 일치 항목에 대해 별도의 프로세스를 호출할 수 있습니다.

  -exec perl -pi -e 's/\r\n/\n/g' {} '+'

더 나은 옵션은 다음과 같습니다.스위스 파일 나이프.하위 디렉터리에서 반복적으로 작동하며 공간과 특수 문자를 적절하게 처리합니다.

당신이 해야 할 일은 다음과 같습니다.

sfk remcr -dir your_project_directory

보너스: sfk는 다른 많은 변환도 합니다.전체 목록은 아래를 참조하십시오.

SFK - The Swiss File Knife File Tree Processor.
Release 1.6.7 Base Revision 2 of May  3 2013.
StahlWorks Technologies, http://stahlworks.com/
Distributed for free under the BSD License, without any warranty.

type "sfk commandname" for help on any of the following.
some commands require to add "-help" for the help text.

   file system
      sfk list       - list directory tree contents.
                       list latest, oldest or biggest files.
                       list directory differences.
                       list zip jar tar gz bz2 contents.
      sfk filefind   - find files by filename
      sfk treesize   - show directory size statistics
      sfk copy       - copy directory trees additively
      sfk sync       - mirror tree content with deletion
      sfk partcopy   - copy part from a file into another one
      sfk mkdir      - create directory tree
      sfk delete     - delete files and folders
      sfk deltree    - delete whole directory tree
      sfk deblank    - remove blanks in filenames
      sfk space [-h] - tell total and free size of volume
      sfk filetime   - tell times of a file
      sfk touch      - change times of a file

   conversion
      sfk lf-to-crlf - convert from LF to CRLF line endings
      sfk crlf-to-lf - convert from CRLF to LF line endings
      sfk detab      - convert TAB characters to spaces
      sfk entab      - convert groups of spaces to TAB chars
      sfk scantab    - list files containing TAB characters
      sfk split      - split large files into smaller ones
      sfk join       - join small files into a large one
      sfk hexdump    - create hexdump from a binary file
      sfk hextobin   - convert hex data to binary
      sfk hex        - convert decimal number(s) to hex
      sfk dec        - convert hex number(s) to decimal
      sfk chars      - print chars for a list of codes
      sfk bin-to-src - convert binary to source code

   text processing
      sfk filter     - search, filter and replace text data
      sfk addhead    - insert string at start of text lines
      sfk addtail    - append string at end of text lines
      sfk patch      - change text files through a script
      sfk snapto     - join many text files into one file
      sfk joinlines  - join text lines split by email reformatting
      sfk inst       - instrument c++ sourcecode with tracing calls
      sfk replace    - replace words in binary and text files
      sfk hexfind    - find words in binary files, showing hexdump
      sfk run        - run command on all files of a folder
      sfk runloop    - run a command n times in a loop
      sfk printloop  - print some text many times
      sfk strings    - extract strings from a binary file
      sfk sort       - sort text lines produced by another command
      sfk count      - count text lines, filter identical lines
      sfk head       - print first lines of a file
      sfk tail       - print last lines of a file
      sfk linelen    - tell length of string(s)

   search and compare
      sfk find       - find words in binary files, showing text
      sfk md5gento   - create list of md5 checksums over files
      sfk md5check   - verify list of md5 checksums over files
      sfk md5        - calc md5 over a file, compare two files
      sfk pathfind   - search PATH for location of a command
      sfk reflist    - list fuzzy references between files
      sfk deplist    - list fuzzy dependencies between files
      sfk dupfind    - find duplicate files by content

   networking
      sfk httpserv   - run an instant HTTP server.
                       type "sfk httpserv -help" for help.
      sfk ftpserv    - run an instant FTP server
                       type "sfk ftpserv -help" for help.
      sfk ftp        - instant anonymous FTP client
      sfk wget       - download HTTP file from the web
      sfk webrequest - send HTTP request to a server
      sfk tcpdump    - print TCP conversation between programs
      sfk udpdump    - print incoming UDP requests
      sfk udpsend    - send UDP requests
      sfk ip         - tell own machine's IP address(es).
                       type "sfk ip -help" for help.
      sfk netlog     - send text outputs to network,
                       and/or file, and/or terminal

   scripting
      sfk script     - run many sfk commands in a script file
      sfk echo       - print (coloured) text to terminal
      sfk color      - change text color of terminal
      sfk alias      - create command from other commands
      sfk mkcd       - create command to reenter directory
      sfk sleep      - delay execution for milliseconds
      sfk pause      - wait for user input
      sfk label      - define starting point for a script
      sfk tee        - split command output in two streams
      sfk tofile     - save command output to a file
      sfk toterm     - flush command output to terminal
      sfk loop       - repeat execution of a command chain
      sfk cd         - change directory within a script
      sfk getcwd     - print the current working directory
      sfk require    - compare version text

   development
      sfk bin-to-src - convert binary data to source code
      sfk make-random-file - create file with random data
      sfk fuzz       - change file at random, for testing
      sfk sample     - print example code for programming
      sfk inst       - instrument c++ with tracing calls

   diverse
      sfk media      - cut video and binary files
      sfk view       - show results in a GUI tool
      sfk toclip     - copy command output to clipboard
      sfk fromclip   - read text from clipboard
      sfk list       - show directory tree contents
      sfk env        - search environment variables
      sfk version    - show version of a binary file
      sfk ascii      - list ISO 8859-1 ASCII characters
      sfk ascii -dos - list OEM codepage 850 characters
      sfk license    - print the SFK license text

   help by subject
      sfk help select   - how dirs and files are selected in sfk
      sfk help options  - general options reference
      sfk help patterns - wildcards and text patterns within sfk
      sfk help chain    - how to combine (chain) multiple commands
      sfk help shell    - how to optimize the windows command prompt
      sfk help unicode  - about unicode file reading support
      sfk help colors   - how to change result colors
      sfk help xe       - for infos on sfk extended edition.

   All tree walking commands support file selection this way:

   1. short format with ONE directory tree and MANY file name patterns:
      src1dir .cpp .hpp .xml bigbar !footmp
   2. short format with a list of explicite file names:
      letter1.txt revenues9.xls report3\turnover5.ppt
   3. long format with MANY dir trees and file masks PER dir tree:
      -dir src1 src2 !src\save -file foosys .cpp -dir bin5 -file .exe

   For detailed help on file selection, type "sfk help select".

   * and ? wildcards are supported within filenames. "foo" is interpreted
   as "*foo*", so you can leave out * completely to search a part of a name.
   For name start comparison, say "\foo" (finds foo.txt but not anyfoo.txt).

   When you supply a directory name, by default this means "take all files".

      sfk list mydir                lists ALL  files of mydir, no * needed.
      sfk list mydir .cpp .hpp      lists SOME files of mydir, by extension.
      sfk list mydir !.cfg          lists all  files of mydir  EXCEPT .cfg

   general options:
      -tracesel tells in detail which files and/or directories are included
                or excluded, and why (due to which user-supplied mask).
      -nosub    do not process files within subdirectories.
      -nocol    before any command switches off color output.
      -quiet    or -nohead shows less output on some commands.
      -hidden   includes hidden and system files and dirs.
      For detailed help on all options, type "sfk help options".

   beware of Shell Command Characters.
      command parameters containing characters < > | ! & must be sur-
      rounded by quotes "". type "sfk filter" for details and examples.

   type "sfk ask word1 word2 ..."   to search ALL help text for words.
   type "sfk dumphelp"              to print  ALL help text.

편집: 주의 사항: 이진 파일이 있는 폴더에서 실행할 경우 파일, 특히 .git 디렉터리가 효과적으로 삭제되므로 주의하십시오.이 경우 전체 폴더에서 sfk를 실행하지 말고 특정 파일 확장자(*.rb, *.py 등)를 선택하십시오.예:sfk remcr -dir chef -file .rb -file .json -file .erb -file .md

find . -not \( -name .svn -prune -o -name .git -prune \) -type f -exec perl -pi -e 's/\r\n|\n|\r/\n/g' {} \;

이것은 당신의 깃 레포를 손상시키지 않기 때문에 훨씬 안전합니다..git, .svn을 .bzr, .hg 또는 사용하는 소스 컨트롤을 목록에 추가하거나 바꿉니다.

OS X에서는 다음과 같은 이점이 있었습니다.

find ./ -type f -exec perl -pi -e 's/\r\n|\n|\r/\n/g' {} \;

경고: 이 명령을 실행하기 전에 디렉터리를 백업하십시오.

현재 승인된 답변은 다음을 사용합니다.find -exec와 함께dos2unix그러나 Bash를 포함한 대다수의 셸은 디렉터리의 모든 파일(경로 이름 확장 또는 글로빙)에서 작동하기 위해 와일드카드를 사용하는 것을 지원하기 때문에 오늘날에는 이것이 불필요합니다.사용하지 않는 답변dos2unix실행 파일, 이미지 및 비디오와 같은 이진 파일, 심지어는 컨텐츠까지 되돌릴 수 없이 손상시키는 순진한 검색 및 검색을 수행하기 때문에 더욱 심각합니다..git디렉토리입니다.

둘다요.dos2unix그리고.unix2dos제가 사용해 본 모든 UNIX 기반 시스템에 미리 설치되어 있는 어디서나 사용할 수 있는 경량 도구입니다. 즉, 이미 시스템에 설치되어 있는 것이 거의 확실합니다.또한 기본적으로 텍스트가 아닌 파일을 건너뛰기 때문에 다른 답변과 달리 전체 디렉토리에서 안전하게 사용할 수 있습니다.

모든 줄 끝을 UNIX 줄 끝(LF)으로 변환하려면 다음과 같이 하십시오.

dos2unix -v *

모든 줄 끝을 CRLF(Windows 줄 끝)로 변환하려면 다음과 같이 하십시오.

unix2dos -v * 

-v/--verbose스위치는 필요하지 않지만 콘솔로 변환되는 파일을 출력합니다.

여기서 sed를 사용하는 경우 해결책:

find . -type f -exec sed -i 's/\r$//' {} \;

-i 인플레이스(in-place)를 의미합니다.-i.bak

's/\r$//'리턴을 할 것입니다.\r각 행의 끝에 있음

 find ./ -type f -name "*.java" -exec perl -pi -e 's/\r\n|\n|\r/\n/g' {} \;

이것은 wsl2에서 모든 Java 파일을 CRLF에서 LF로 변경하는 데 효과가 있었습니다.

다른 것과 동일하지만 node.js가 있음

find ./src/test/resources/com/sonalake/bss/tests/bdd/ -type f -exec node -e "require('fs'); const val = fs.readFileSync(process.argv[1], 'utf8'); fs.writeFileSync(process.argv[1], val.replace(/\r\n/g, '\n'))" {} ';'
// load file system module
require('fs');
// read file
const val = fs.readFileSync(process.argv[1], 'utf8');
// replace file contents
fs.writeFileSync(process.argv[1], val.replace(/\r\n/g, '\n'))

언급URL : https://stackoverflow.com/questions/7068179/convert-line-endings-for-whole-directory-tree-git

반응형