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.

おすすめ記事