programing

새 줄 서식을 Mac에서 Windows로 변환

subpage 2023. 6. 18. 16:01
반응형

새 줄 서식을 Mac에서 Windows로 변환

Mac에서 생성된 .sql 덤프 파일을 Windows에서 읽을 수 있는 파일로 변환하는 변환 유틸리티/스크립트가 필요합니다.이것은 제가 여기서 겪었던 문제의 연속입니다.텍스트 파일의 줄 바꿈 형식에 문제가 있는 것 같습니다. 변환할 도구를 찾을 수 없습니다.

Windows 사용carriage return+line feed새 줄의 경우:

\r\n

유닉스에서만 사용Line feed새 줄의 경우:

\n

결론적으로, 모든 발생을 간단히 대체합니다.\n타고\r\n.
둘다요.unix2dos그리고.dos2unix는 기본적으로 Mac OS X에서 사용할 수 없습니다.
다행히도, 당신은 간단히 사용할 수 있습니다.Perl또는sed작업 수행:

sed -e 's/$/\r/' inputfile > outputfile                # UNIX to DOS  (adding CRs)
sed -e 's/\r$//' inputfile > outputfile                # DOS  to UNIX (removing CRs)
perl -pe 's/\r\n|\n|\r/\r\n/g' inputfile > outputfile  # Convert to DOS
perl -pe 's/\r\n|\n|\r/\n/g'   inputfile > outputfile  # Convert to UNIX
perl -pe 's/\r\n|\n|\r/\r/g'   inputfile > outputfile  # Convert to old Mac

코드 조각 원본:
http://en.wikipedia.org/wiki/Newline#Conversion_utilities

이것은 Anne의 답변의 개선된 버전입니다. 펄을 사용하는 경우 새 파일을 생성하는 대신 'in-place' 파일에서 편집을 수행할 수 있습니다.

perl -pi -e 's/\r\n|\n|\r/\r\n/g' file-to-convert  # Convert to DOS
perl -pi -e 's/\r\n|\n|\r/\n/g'   file-to-convert  # Convert to UNIX

홈브루와 함께 unix2dos를 설치할 수 있습니다.

brew install unix2dos

그러면 다음을 수행할 수 있습니다.

unix2dos file-to-convert

dos 파일을 unix로 변환할 수도 있습니다.

dos2unix file-to-convert

그냥 해요tr삭제:

tr -d "\r" <infile.txt >outfile.txt

당신은 아마도 unix2dos를 원할 것입니다.

$ man unix2dos

NAME
       dos2unix - DOS/MAC to UNIX and vice versa text file format converter

SYNOPSIS
           dos2unix [options] [-c CONVMODE] [-o FILE ...] [-n INFILE OUTFILE ...]
           unix2dos [options] [-c CONVMODE] [-o FILE ...] [-n INFILE OUTFILE ...]

DESCRIPTION
       The Dos2unix package includes utilities "dos2unix" and "unix2dos" to convert plain text files in DOS or MAC format to UNIX format and vice versa.  Binary files and non-
       regular files, such as soft links, are automatically skipped, unless conversion is forced.

       Dos2unix has a few conversion modes similar to dos2unix under SunOS/Solaris.

       In DOS/Windows text files line endings exist out of a combination of two characters: a Carriage Return (CR) followed by a Line Feed (LF).  In Unix text files line
       endings exists out of a single Newline character which is equal to a DOS Line Feed (LF) character.  In Mac text files, prior to Mac OS X, line endings exist out of a
       single Carriage Return character. Mac OS X is Unix based and has the same line endings as Unix.

실행할 수 있습니다.unix2dosCygwin을 사용하는 DOS/Windows 컴퓨터 또는 MacPorts를 사용하는 Mac에 설치할 수 있습니다.

  1. 홈브루와 함께 dos2unix 설치
  2. 달려.find ./ -type f -exec dos2unix {} \;현재 폴더 내의 모든 줄 끝을 재귀적으로 변환합니다.

vim또한 UNIX에서 DOS 형식으로 파일을 변환할 수 있습니다.예:

vim hello.txt <<EOF
:set fileformat=dos
:wq
EOF

반대로 DOS에서 UNIX로 전환해야 하는 경우:

vim hello.txt <<EOF
:set fileformat=unix
:wq
EOF

여기 정말 간단한 접근법이 있습니다. 저에게 잘 작동했습니다. David Schmeits의 웹로그를 제공합니다.

cat foo | col -b > foo2

여기서 foo는 줄 끝에 Control+M 문자가 있는 파일이고, foo2는 작성 중인 새 파일입니다.

다음은 정상성 검사와 함께 위의 답변을 기반으로 한 전체 스크립트이며 Mac OS X에서 작동하며 다른 Linux/Unix 시스템에서도 작동해야 합니다(테스트되지는 않았지만).

#!/bin/bash

# http://stackoverflow.com/questions/6373888/converting-newline-formatting-from-mac-to-windows

# =============================================================================
# =
# = FIXTEXT.SH by ECJB
# =
# = USAGE:  SCRIPT [ MODE ] FILENAME
# =
# = MODE is one of unix2dos, dos2unix, tounix, todos, tomac
# = FILENAME is modified in-place
# = If SCRIPT is one of the modes (with or without .sh extension), then MODE
# =   can be omitted - it is inferred from the script name.
# = The script does use the file command to test if it is a text file or not,
# =   but this is not a guarantee.
# =
# =============================================================================

clear
script="$0"
modes="unix2dos dos2unix todos tounix tomac"

usage() {
    echo "USAGE:  $script [ mode ] filename"
    echo
    echo "MODE is one of:"
    echo $modes
    echo "NOTE:  The tomac mode is intended for old Mac OS versions and should not be"
    echo "used without good reason."
    echo
    echo "The file is modified in-place so there is no output filename."
    echo "USE AT YOUR OWN RISK."
    echo
    echo "The script does try to check if it's a binary or text file for sanity, but"
    echo "this is not guaranteed."
    echo
    echo "Symbolic links to this script may use the above names and be recognized as"
    echo "mode operators."
    echo
    echo "Press RETURN to exit."
    read answer
    exit
}

# -- Look for the mode as the scriptname
mode="`basename "$0" .sh`"
fname="$1"

# -- If 2 arguments use as mode and filename
if [ ! -z "$2" ] ; then mode="$1"; fname="$2"; fi

# -- Check there are 1 or 2 arguments or print usage.
if [ ! -z "$3" -o -z "$1" ] ; then usage; fi

# -- Check if the mode found is valid.
validmode=no
for checkmode in $modes; do if [ $mode = $checkmode ] ; then validmode=yes; fi; done
# -- If not a valid mode, abort.
if [ $validmode = no ] ; then echo Invalid mode $mode...aborting.; echo; usage; fi

# -- If the file doesn't exist, abort.
if [ ! -e "$fname" ] ; then echo Input file $fname does not exist...aborting.; echo; usage; fi

# -- If the OS thinks it's a binary file, abort, displaying file information.
if [ -z "`file "$fname" | grep text`" ] ; then echo Input file $fname may be a binary file...aborting.; echo; file "$fname"; echo; usage; fi

# -- Do the in-place conversion.
case "$mode" in
#   unix2dos ) # sed does not behave on Mac - replace w/ "todos" and "tounix"
#       # Plus, these variants are more universal and assume less.
#       sed -e 's/$/\r/' -i '' "$fname"             # UNIX to DOS  (adding CRs)
#       ;;
#   dos2unix )
#       sed -e 's/\r$//' -i '' "$fname"             # DOS  to UNIX (removing CRs)
#           ;;
    "unix2dos" | "todos" )
        perl -pi -e 's/\r\n|\n|\r/\r\n/g' "$fname"  # Convert to DOS
        ;;
    "dos2unix" | "tounix" )
        perl -pi -e 's/\r\n|\n|\r/\n/g'   "$fname"  # Convert to UNIX
        ;;
    "tomac" )
        perl -pi -e 's/\r\n|\n|\r/\r/g'   "$fname"  # Convert to old Mac
        ;;
    * ) # -- Not strictly needed since mode is checked first.
        echo Invalid mode $mode...aborting.; echo; usage
        ;;
esac

# -- Display result.
if [ "$?" = "0" ] ; then echo "File $fname updated with mode $mode."; else echo "Conversion failed return code $?."; echo; usage; fi

Yosemite OSX에서 다음 명령을 사용합니다.

sed -e 's/^M$//' -i '' filename

어디서^M+를 누른 다음 V을 누르면 시퀀스가 실행됩니다.

매번 펄 원라이너를 입력하는 것이 귀찮기 때문에 짧은 펄 스크립트에서 펄을 사용하여 Anne과 Joseph H의 답변을 확장합니다.
"unix2dos.pl "과 같은 이름의 파일을 만들고 경로의 디렉토리에 넣습니다.다음 두 줄을 포함하도록 파일을 편집합니다.

#!/usr/bin/perl -wpi
s/\n|\r\n/\r\n/g;

"which perl"이 시스템에서 "/usr/bin/perl"을 반환한다고 가정합니다.파일을 실행 파일로 만듭니다(chmodu+x unix2dos.pl ).

예:
> "에하세요안" > xxx
) od -c xxx(파일 이름은 nl입니다.)
0000000 안녕하세요 \n

.pl xxxunix2dos.pl xxx
-c xxx(crf로 끝나는지 확인)
\n0000000 파일 \r \n

왼쪽 패널의 Xcode 9에서 프로젝트 탐색기에서 파일을 열거나 선택합니다.파일이 없으면 프로젝트 탐색기에 파일을 약으로 저장합니다.

오른쪽 패널에서 텍스트 설정을 찾고을 Windows(CRLF)변경합니다.

XCode 화면screendump from XCode 덤프

언급URL : https://stackoverflow.com/questions/6373888/converting-newline-formatting-from-mac-to-windows

반응형