简体   繁体   中英

Using sed to append part of a string to the front of the string

In Linux, I have a string and wish to use sed to append a number found in the string to the front of it, with a colon afterwards. For example, I have the string

word word word 01 word word 02 word word word word 03 word

and wish to have

03:word word word 01 word word 02 word word word word 03 word

I can use

sed 's/^/:/' 

to append the colon to the front, but for each individual string I want to copy the number in the 03 position to the front as well.

You can use this:

sed -r 's/(.*[^0-9])([0-9]+)/\2:\1\2/' <<< "$string"

I'm using the substitute command s . (.*[^0-9]) captures (greedy) everything until the last number in the string into subpattern 1. The number itself ([0-9]+) goes to subpattern 2.

In the replacement pattern we print subpattern 2 in front of 2 and add the colon between them.

Since you're treating the input like columns, it might be better served by awk.

Here's a column-ish approach with sed:

sed -r 's/^(([^ ]+ ){11})([^ ]+)/\3:\1\3/'

(if your "03" column ever gets changed, just change the {11} to `{yournewcolumnnumber-1})


with awk, things are a bit more readable

awk '{print $12 ":" $0}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM