0

I have the following string:

"5  S comment=whatever Unspecific text fruit=apple animal=mouse sky=blue"

I need to move to end of the string, all that begin with comment to the word text.

The start is always be comment= and the delimiter is always fruit. The value between comment=... and fruit delimiter is variable.

any suggestion?

2
  • Can there be more than one comment= and/or fruit in that string? Do you need that process for every line of a file, or just in a string stored in a shell variable? Can that string contain newline characters? Commented May 27, 2015 at 14:57
  • Yes, there may be many lines in the file. And only one field with comment= for each line. Also, the end of the string can be variable, this end could be sky=blue or raze=human, or whatever word, is unspecific. and i using bash . Thanks for reply. Commented May 27, 2015 at 15:28

1 Answer 1

1

If that string is in a shell variable, and that shell is zsh, you can do:

string='5  S comment=whatever Unspecific text fruit=apple animal=mouse sky=blue'
new_string=${string/(#b)(comment=*)(fruit*)/$match[2] $match[1]}

If that shell is ksh93:

new_strong=${string//@(comment=*)@(fruit*)/\2 \1}

If that shell is a POSIX shell (like those two, bash or the sh of modern systems):

a=${string%%comment=*}
b=${string#"$a"}
b=${b%fruit*}
c=${string#"$a$b"}
new_string=$a$c$b

For each line of a file:

sed 's/\(comment=.*\)\(fruit.*\)/\2 \1/' < file

All three would match the part from the left-most comment= to the rightmost fruit if there were more than one per line/string.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.