使用 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

相关内容