如何在文件中的各个数字之间插入空格?

zar*_*ara 6 linux sed

我的数据看起来像:

$ cat input
1212103122
1233321212
0000022221
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像:

$ cat output
1 2 1 2 1 0 3 1 2 2
1 2 3 3 3 2 1 2 1 2
0 0 0 0 0 2 2 2 2 1
Run Code Online (Sandbox Code Playgroud)

我试过:

sed -i 's// /g' input > output
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

有什么建议?

Hea*_*ohn 9

这对我有用:

sed 's/./& /g' input > output

$ cat input
1212103122
1233321212
0000022221

$ cat output
1 2 1 2 1 0 3 1 2 2 
1 2 3 3 3 2 1 2 1 2 
0 0 0 0 0 2 2 2 2 1 
Run Code Online (Sandbox Code Playgroud)


小智 5

这个给你:

sed 's/\(.\{1\}\)/\1 /g' input > output
Run Code Online (Sandbox Code Playgroud)

如果您想就地保存更改:

sed -i 's/\(.\{1\}\)/\1 /g' input
Run Code Online (Sandbox Code Playgroud)

这个怎么运作:

s/\(.\{1\}\)/\ /g 将在每 1 个字符后添加一个空格。

例如,如果您想要一个输出文件,如:

12 12 10 31 22
12 33 32 12 12
00 00 02 22 21
Run Code Online (Sandbox Code Playgroud)

您可以将我的答案编辑为:

sed -i 's/\(.\{2\}\)/\1 /g'
Run Code Online (Sandbox Code Playgroud)

所以它会在每 2 个字符后添加一个空格。

此外,/\1 /与 , 相同/&,会添加一个空格。例如,添加三个:/\1 //& /。您有更多选择可以使用。Sed 是一个超级强大的工具。

另外是的,正如@Law29 提到的,如果您不删除,这将在每行的末尾留下一个空格,因此要在添加空格的同时删除它们,您可以s/ $//在给定解决方案的末尾添加一个,这样做:

sed 's/./& /g; s/ $//'
Run Code Online (Sandbox Code Playgroud)

我希望这会有所帮助。

  • 使用 `-r` 可以删除大部分反斜杠,使其更清晰。`{1}` 不是必需的,如果这就是你匹配的全部,那么你甚至不需要捕获组, (2认同)