regex Bash脚本将行的内容替换为后续行中的信息(sed)

bmvo0sr5  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(78)

我有一个File.txt文件,在方括号[]中列出了几个项目和后续行中的其他细节:

item name1,
item name2,
item name3,
item name4,
some text
on several lines
detail name1;
detail name2[moreinfo];
detail name3[can contain numbers and characters:1];
detail name4;

我想修改它,以便在前面的行中追加每个项目的详细信息,以获得以下预期输出:

item name1,
item name2[moreinfo],
item name3[can contain numbers and characters:1],
item name4,
some text
on several lines
detail name1;
detail name2[moreinfo];
detail name3[can contain numbers and characters:1];
detail name4;

当项目的数量未知时,有没有简单的sed表达式可以做到这一点?我想要类似以下的内容:

sed -i '/detail \(.*\)\[\(.*\)\]/ s/item \1/item \1\[\2\]/g' File.txt

但我知道反向引用不是这样的

6tdlim6h

6tdlim6h1#

下面是一个Perl解决方案:

perl -0777 -pe 's/^item (.*),(?=(?:.|\n)*^detail \1(\[.*\]))/item $1$2,/mg'

它使用-0777(从Perl 5.36开始可以缩短为-g)将整个文件作为单个字符串读取。替换使用(?=...)前瞻Assert来搜索相应的细节。

yhqotfr8

yhqotfr82#

awk '
    FNR==NR{
        if ($0 ~ /^detail /){
            sub(/^detail /,"item ")
            sub(/;$/,",")
            key=value=$0
            sub(/\[.*\]/,"",key)
            a[key] = value
        }
        next
    }   
    {
        if ($0 in a) 
            print a[$0]
        else
            print
    }
' file file
omvjsjqw

omvjsjqw3#

使用tac和任何awk

$ tac file |
    awk -F'[[ ,;]' '
        ($1 == "detail") && match($0,/\[.*]/) { det[$2] = substr($0,RSTART,RLENGTH) }
        ($1 == "item") && ($2 in det) { sub(/,$/,""); $0 = $0 det[$2] "," }
        { print }
    ' |
    tac
item name1,
item name2[moreinfo],
item name3[can contain numbers and characters:1],
item name4,
some text
on several lines
detail name1;
detail name2[moreinfo];
detail name3[can contain numbers and characters:1];
detail name4;
uqzxnwby

uqzxnwby4#

这可能对你有用(GNU sed):

sed -E 'H;$!d;x
        :a;s/(\nitem ([^,]+))(,.*\ndetail \2(\[[^[]+\]);)/\1\4\3/;ta;s/.//' file

将文件拖到保留空间中,然后使用模式匹配对项目和详细信息的相同名称进行替换,在匹配的项目名称后的详细信息后面插入一个带括号的字符串。当没有更多的匹配项时,删除引入的换行符并打印结果。
另一种稍短的解决方案:

sed -zE ':a;s/(item ([^,]+))(,.*detail \2(\[[^[]+\]);)/\1\4\3/;ta' file

相关问题