sed를 사용하여 하위 문자열의 일부만 변경

sed를 사용하여 하위 문자열의 일부만 변경

어딘가에서 복사된 숫자가 포함된 파일이 있습니다. 다음과 같습니다.

{02   12     04 01 07 10 11 06 08 05 03    15     13     00    14     09},
{14   11     02 12 04 07 13 01 05 00 15    10     03     09    08     06},
{04   02     01 11 10 13 07 08 15 09 12    05     06     03    00     14},
{11   08     12 07 01 14 02 13 06 15 00    09     10     04    05     03}

이제 각 숫자 뒤에 쉼표를 추가해야 합니다(기본적으로 C++ 배열로 만들기 위해). 나는 sed를 사용해 본다:

cat file.txt | sed -r "s/ /, /g"

하지만 이것은 각 공백 앞에 쉼표를 넣는 반면, 나는 숫자 뒤에만 쉼표를 넣기를 원합니다.

을 사용하면 cat file.txt | sed -r "s/[0123456789] /, /g"교체 전과 동일한 번호를 얻을 수 없습니다. 그래서 하위 문자열의 특정 부분만 변경하고 싶습니다.

어떻게 해야 하나요?

답변1

cat file.txt | sed -r 's/([0-9]+)/\1,/g'

{02,   12,     04, 01, 07, 10, 11, 06, 08, 05, 03,    15,     13,     00,    14,     09,},
{14,   11,     02, 12, 04, 07, 13, 01, 05, 00, 15,    10,     03,     09,    08,     06,},
{04,   02,     01, 11, 10, 13, 07, 08, 15, 09, 12,    05,     06,     03,    00,     14,},
{11,   08,     12, 07, 01, 14, 02, 13, 06, 15, 00,    09,     10,     04,    05,     03,}

설명하다:

First capturing group ([0-9]+)

Match a single character (i.e. number) present in the table [0-9]+ 
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

In other words, the [0-9]+ pattern matches an integer number (without decimals) even Inside longer strings, even words.
\1 is called a "back reference" or "special escapes" in the sed documentation. It refers to the corresponding matching sub-expressions in the regexp. In other words, in this example, it inserts the contents of each captured number in the table followed by comma.

답변2

공백 뒤에 공백이 있으면 간단히 쉼표로 바꿀 수 있습니다.

sed 's/  */,/g' file

(일부 줄의 시작 부분에 공백이 있으면 복사 붙여넣기 오류일 뿐입니다.)

답변3

어때요?

sed 's/ \+/, /g' file
{02, 12, 04, 01, 07, 10, 11, 06, 08, 05, 03, 15, 13, 00, 14, 09},
{14, 11, 02, 12, 04, 07, 13, 01, 05, 00, 15, 10, 03, 09, 08, 06},
{04, 02, 01, 11, 10, 13, 07, 08, 15, 09, 12, 05, 06, 03, 00, 14},
{11, 08, 12, 07, 01, 14, 02, 13, 06, 15, 00, 09, 10, 04, 05, 03}

답변4

이 perl 명령은 숫자와 공백 사이에 쉼표를 추가합니다.

perl -pe 's/(?<=\d)(?=\s)/,/g' file

관련 정보