You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用sed或awk命令复制指定字符串片段并粘贴到目标位置?

用sed或awk实现字符串片段的提取与插入

嘿,这个需求其实用sed或者awk都能轻松搞定,我给你分两种方法详细说说:

使用sed实现

sed擅长处理文本替换和捕获,我们可以分两步完成,也可以合并成一行命令:

分步操作

  1. 先从源字符串中提取目标片段is the:
# 捕获"this"和"string"之间的部分,输出提取的片段
fragment=$(echo "this is the string" | sed -n 's/^this\( is the \)string$/\1/p')

这里的正则^this\( is the \)string$精准匹配整个源字符串,用\(\)捕获中间的is the,最后用\1输出捕获内容。

  1. 将提取的片段插入到目标字符串this word的中间(也就是this和word之间):
echo " this word " | sed "s/\( this \)\(word \)/\1$fragment\2/"

这里用\( this \)和\(word \)捕获目标字符串的前后部分,然后把片段插入到两者之间。

合并成一行命令

如果想一步到位,可以把提取和插入合并:

echo " this word " | sed "s/\( this \)\(word \)/\1$(echo "this is the string" | sed -n 's/^this\( is the \)string$/\1/p')\2/"

执行后会输出:this is the word

使用awk实现

awk的文本处理能力更灵活,既可以通过正则匹配提取片段,也可以通过字段拆分来获取:

方法一:正则匹配提取片段

awk -v src="this is the string" -v dest=" this word " '
BEGIN {
    # 用match函数定位" is the "的位置,然后提取
    match(src, / is the /)
    fragment = substr(src, RSTART, RLENGTH)
    # 将片段插入到dest的"this "之后
    sub(/this /, "this " fragment, dest)
    print dest
}'

执行后同样会输出:this is the word

方法二:字段拆分提取片段

因为源字符串this is the string是按空格分隔的4个字段,中间的is和the正好是我们需要的部分,加上前后空格就可以得到is the:

awk -v src="this is the string" -v dest=" this word " '
BEGIN {
    split(src, fields, " ")
    fragment = " " fields[2] " " fields[3] " "
    sub(/this /, "this " fragment, dest)
    print dest
}'

这种方法适合字段结构固定的场景,可读性更强。

内容的提问来源于stack exchange,提问作者aweeey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:32:43