$ sed's/This is my \([^,]*\),.*is \(.*\)/\1:\2/g' my.txt
cat:betty
dog:frank
fish:george
goat:adam
上面这个例子中的正则表达式有点复杂,解开如下(去掉转义字符): 正则为:This is my ([^,]*),.*is (.*) 匹配为:This is my (cat),……….is (betty) 然后:\1就是cat,\2就是betty
用N命令合并行
N命令的作用是将文件中的两行当成一行来处理,其分隔符是“\n”。举例如下: sed 'N;s/\n/,/' file.txt
# 源文件内容file.txt
This is my cat
my cat's name is betty
This is my dog
my dog's name is frank
This is my fish
my fish's name is george
This is my goat
my goat's name is adam
# 用N命令转换后,缓存中的文件内容变成了
This is my cat\n my cat's name is betty
This is my dog\n my dog's name is frank
This is my fish\n my fish's name is george
This is my goat\n my goat's name is adam