sed的反向输入顺序 [英] Reverse input order with sed

查看:83
本文介绍了sed的反向输入顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我们称其为 a.txt,并且该文件包含以下文本行

I have a file, lets call it 'a.txt' and this file contains the following text line

do to what

我想知道SED命令是什么来颠倒此文本的顺序以使其看起来像

I'm wondering what the SED command is to reverse the order of this text to make it look like

what to do

我必须进行某种附加吗?就像将'do'附加到'to'一样,它看起来就像

Do I have to do some sort of append? Like append 'do' to 'to' so it would look like

到++ do(使用++只是为了清楚起见)

to ++ do (used ++ just to make it clear)

推荐答案

答案



该问题被标记为,我的第一个答案是:

sed answer

As this question was tagged sed, my 1st answer was:

首先(使用仲裁 _ 标记当 a.txt 包含做某事时所查看的空格:

First (using arbitraty _ to mark viewed spaces, when a.txt contain do to what:

sed -e '
    :a;
    s/\([^_]*\) \([^ ]*\)/\2_\1/;
    ta;
    y/_/ /;
   ' a.txt
what to do

比,当 a.txt 包含<$ c时$ c>做到什么:

sed -e '
    :a;
    s/^\(\|.* \)\([^+ ]\+\) \2\([+]*\)\(\| .*\)$/\1\2\3+\4/g;
    ta;
    :b;
    s/\([^_]*\) \([^ ]*\)/\2_\1/;
    tb;
    y/_/ /;
   ' <<<'do to to to what'
what to++ do

每个被压抑的重复单词有一个 +

There is one + for each supressed duplicated word:

sed -e ':a;s/^\(\|.* \)\([^+ ]\+\) \2\([+]*\)\(\| .*\)$/\1\2\3+\4/g;ta;
        :b;s/\([^_]*\) \([^ ]*\)/\2_\1/;tb;
        y/_/ /;' <<<'do do to what what what what'
what+++ to do+



bash 答案



但是由于有很多人在搜索简单的解决方案,有一种简单的方法:

bash answer

But as there is a lot of people searching for simple bash solutions, there is a simple way:

xargs < <(uniq <(tac <(tr \  \\n <<<'do do to what what what what')))
what to do

这可以写成:

tr \  \\n <<<'do do to what what what what' | tac | uniq | xargs 
what to do

甚至带有某些脚本的问题:

or even with some bash scripting:

revcnt () { 
    local wrd cnt plut out="";
    while read cnt wrd; do
        printf -v plus %$((cnt-1))s;
        out+=$wrd${plus// /+}\ ;
    done < <(uniq -c <(tac <(tr \  \\n )));
    echo $out
}

会这样做:

revcnt <<<'do do to what what what what' 
what+++ to do+



或作为 pure



Or as pure bash

revcnt() { 
    local out i;
    for ((i=$#; i>0; i--))
    do
        [[ $out =~ ${!i}[+]*$ ]] && out+=+ || out+=\ ${!i};
    done;
    echo $out
}

其中提交的字符串必须作为参数提交:

where submited string have to be submitted as argument:

revcnt do do to what what what what
what+++ to do+

或者如果需要处理标准输入(或来自文件):

Or if prossessing standard input (or from file) is required:

revcnt() { 
    local out i arr;
    while read -a arr; do
        out=""
        for ((i=${#arr[@]}; i--; 1))
        do
            [[ $out =~ ${arr[i]}[+]*$ ]] && out+=+ || out+=\ ${arr[i]};
        done;
        echo $out;
    done
}

因此您可以处理多行:

revcnt <<eof
do to what
do to to to what
do do to what what what what
eof
what to do
what to++ do
what+++ to do+

这篇关于sed的反向输入顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆