Skip to content
Advertisement

How cut characters from string and put it at the end- In shell

I want to be able to do the following:

String1= "HELLO 3002_3322 3.2.1.log"

And get output like:

output = "3002_3322 3.2.1.log HELLO"

I know the command sed is able to do this but I need some guidance.

Thanks!

Advertisement

Answer

In sed you can do:

sed 's/([^[:blank:]]*)[[:blank:]]*(.*)/2 1/'

Which outputs 3002_3322 3.2.1.log HELLO.

Explanation

  1. The first word is captured by ([^[:blank:]]*) The () means I want to capture this group to use later. [:blank:] is a POSIX character class for whitespace characters. You can see the other POSIX character classes here:

http://www.regular-expressions.info/posixbrackets.html

The outer [] means match anyone of the characters, and the ^ means any character except those listed in the character class. Finally the * means any number of occurrences (including 0) of the previous character. So in total [^[:blank:]]* this means match a group of characters that are not whitespace, or the first word. We have to do this somewhat complicated regex because POSIX sed only supports BRE (basic regex) which is greedy matching, and to find the first word we want non-greedy matching.

  1. [[:blank:]]*, as explained above, this means match a group of consecutive whitespaces.

  2. (.*) This means capture the rest of the line. The . means any single character, so combined with the * it means match the rest of the characters.

  3. For the replacement, the 2 1 means replace the pattern we matched with the 2nd capture group, a space, then the first capture group.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement