如何使用sed在每行首个数字后添加指定字符?
问题:在每行首个数字后添加
,\" 输入内容(input.txt)
1 In the beginning, God created the heavens and the earth. 2 The earth was without form and void, and darkness was over the face of the deep. And the Spirit of God was hovering over the face of the waters. 3 And God said, “Let there be light,” and there was light. 4 And God saw that the light was good. And God separated the light from the darkness. 5 God called the light Day, and the darkness he called Night. And there was evening and there was morning, the first day. 6 And God said, “Let there be an expanse in the midst of the waters, and let it separate the waters from the waters.” 7 And God made the expanse and separated the waters that were under the expanse from the waters that were above the expanse. And it was so. 8 And God called the expanse Heaven. And there was evening and there was morning, the second day. 9 And God said, “Let the waters under the heavens be gathered together into one place, and let the dry land appear.” And it was so. 10 God called the dry land Earth, and the waters that were gathered together he called Seas. And God saw that it was good.
期望输出
1,"In the beginning, God created the heavens and the earth. 2,"The earth was without form and void, and darkness was over the face of the deep. And the Spirit of God was hovering over the face of the waters. 3,"And God said, “Let there be light,” and there was light. 4,"And God saw that the light was good. And God separated the light from the darkness. 5,"God called the light Day, and the darkness he called Night. And there was evening and there was morning, the first day. 6,"And God said, “Let there be an expanse in the midst of the waters, and let it separate the waters from the waters.” 7,"And God made the expanse and separated the waters that were under the expanse from the waters that were above the expanse. And it was so. 8,"And God called the expanse Heaven. And there was evening and there was morning, the second day. 9,"And God said, “Let the waters under the heavens be gathered together into one place, and let the dry land appear.” And it was so. 10,"God called the dry land Earth, and the waters that were gathered together he called Seas. And God saw that it was good.
当前尝试的MWE
#!/bin/bash cat input.txt|sed 's/ /,"/'
正确的sed实现方法
你的原命令问题在于只匹配了普通空格,但输入中数字后面的空白是非断空格(NBSP),而且没有精准定位到行首数字的位置。正确写法可以精准匹配行首数字序列,替换后续空白并插入目标字符:
sed 's/^\([0-9]\+\)\s/\1,"/' input.txt
命令解释:
^:锁定行的开头位置\([0-9]\+\):捕获一个或多个连续数字(比如1、10这类章节号),用\1引用捕获到的内容\s:匹配任意空白字符(兼容普通空格、非断空格、制表符等)\1,":保留捕获的数字,添加,\"替换掉原来的空白部分
如果确认数字后只有非断空格,也可以直接匹配该字符的UTF-8编码(但\s更通用):
sed 's/^\([0-9]\+\)\xc2\xa0/\1,"/' input.txt
内容的提问来源于stack exchange,提问作者Biki Teron
相关产品推荐
相关产品推荐

