reverse the order of characters in a string

后端 未结 13 981
逝去的感伤
逝去的感伤 2020-12-04 15:03

In string \"12345\", out string \"54321\". Preferably without third party tools and regex.

相关标签:
13条回答
  • 2020-12-04 15:56

    Nobody appears to have posted a sed solution, so here's one that works in non-GNU sed (so I wouldn't consider it "3rd party"). It does capture single characters using the regex ., but that's the only regex.

    In two stages:

    $ echo 123456 | sed $'s/./&\\\n/g' | sed -ne $'x;H;${x;s/\\n//g;p;}'
    654321
    

    This uses bash format substitution to include newlines in the scripts (since the question is tagged bash). It works by first separating the input string into one line per character, and then by inserting each character into the beginning of the hold buffer.

    • x swaps the hold space and the pattern space, and
    • H H appends the (current) pattern space to the hold space.

    So for every character, we place that character into the hold space, then append the old hold space to it, thus reversing the input. The final command removes the newlines in order to reconstruct the original string.

    This should work for any single string, but it will concatenate multi-line input into a single output string.

    0 讨论(0)
提交回复
热议问题