Reputation: 11
I am curious how can I do the following thing with sed: I need to wrap certain two words in single quotes in each line. For example, the following text:
I did it like this:
cat file |sed "s/[^ ][^ ]*/'&'/g"
result:
'the-first-word' '-firstPrameter' 'value' '-secondParameter' 'value' '-thirdParameter' 'value' '-fourthParameter' 'value'
But it is wrapping every word.
It should be like this, skip the first word and wrap only parameter and value:
the-first-word '-firstPrameter value' '-secondParameter value' '-thirdParameter value' '-fourthParameter value'
Upvotes: 1
Views: 4006
Reputation: 113934
In your example, the first word is at the start of the line. Thus, if we quote all words that have a space in front of them, then we will quote all but the first:
sed "s/ \([^ ]\+\)/ '\\1'/g" file
the-first-word '-firstPrameter' 'value' '-secondParameter' 'value' '-thirdParameter' 'value' '-fourthParameter' 'value'
If your sed
supports the -r
flag (GNU), then we can remove some of those backslashes:
sed -r "s/ ([^ ]+)/ '\\1'/g" file
On Mac OSX, replace -r
with -E
.
Upvotes: 1
Reputation: 20506
sed "s/ \([^ ]* [^ ]*\)/ '\\1'/g" file
$cat file.txt
the-first-word -firstPrameter value -secondParameter value -thirdParameter value -fourthParameter value
$sed "s/ \([^ ]* [^ ]*\)/ '\\1'/g" file.txt
the-first-word '-firstPrameter value' '-secondParameter value' '-thirdParameter value' '-fourthParameter value'
Upvotes: 1