Reputation: 107
I am using sed to remove some text and replace it, I can get most of it accomplished but I'm at a stand still with replacing the string of 5 colon's before and the one after of it. Any thoughts on where I'm going wrong?
Text file I have:
The user name1 ONE:TWO:THREE:FOUR:FIVE:NewName:SIX
The user name2 SEVEN:EIGHT:NINE:TEN:ELEVEN:NewName:TWELVE
The user name3 Thirteen:Fourteen:Fifteen:Sixteen:NewName:Seventeen
command:
sed 's/^/ The user /'| sed 's/:.*/ My New Name is/'
Output:
The user name1 My New Name is
Expected output:
The user name1 My New Name is NewName
Upvotes: 1
Views: 900
Reputation: 133508
With your shown samples please try following.
awk -F'[ :]' '{print $1,$2,$3,"My New Name is",$(NF-1)}' Input_file
Explanation: Simple explanation would be, setting field separator as space OR colon here for all lines. Then simply printing 1st, 2nd, 3rd fields followed by string May Name is
followed by 2nd last field of current line as per requirements of OP.
Upvotes: 2
Reputation: 626802
You can use
sed '/^The user / s/[^: ]*:.*:\(.*\):.*/My New Name is \1/' file
See the online demo:
s='The user name1 ONE:TWO:THREE:FOUR:FIVE:NewName:SIX
The user name2 SEVEN:EIGHT:NINE:TEN:ELEVEN:NewName:TWELVE
The user name3 Thirteen:Fourteen:Fifteen:Sixteen:NewName:Seventeen'
sed '/^The user / s/[^: ]*:.*:\(.*\):.*/ My New Name is \1/' <<< "$s"
# =>
# The user name1 My New Name is NewName
# The user name2 My New Name is NewName
# The user name3 My New Name is NewName
Here,
/^The user /
- finds the lines that start with The user
s/[^: ]*:.*:\(.*\):.*/ My New Name is \1/
finds
[^: ]*
- zero or more chars other than a colon and space:.*:
- :
, any text, :
\(.*\)
- Group 1 (\1
): any text:.*
- :
and the rest of the string.\1
is the replacement placeholder, the contents of Group 1.Upvotes: 1
Reputation: 785128
It is easier to use awk
:
awk '{print $1, $2, $3, "My New Name is", a[split($NF, a, /:/)-1]}' file
The user name1 My New Name is NewName
The user name2 My New Name is NewName
The user name3 My New Name is NewName
Upvotes: 2