Friday, 15 January 2016

How To Use & In Sed Command In Unix/Linux

In this article we will see when and how to use &, a special character, in sed command.

Scenario:1

Whenever word knowledge is found we have to replace the same with (knowledge). We can do the same very easily by using simple sed replacement.

$ sed 's/knowledge/(knowledge)/' F_Input_File.txt

Here, we want to replace knowledge with (knowledge) hence we have used (knowledge) as replacement string.

Scenario:2

Lets assume, you have to incorporate first 3 digit of a phone number in brackets ( as shown below)

1234567890 => (123)4567890
0987654321 => (098)7654321

You might try to use something like below:

$ sed 's/[[:digit:]][[:digit:]][[:digit:]]/([[:digit:]][[:digit:]][[:digit:]])/' F_Input_File.txt

This would not provide us the required and provide us below output:

([[:digit:]][[:digit:]][[:digit:]])4567890
([[:digit:]][[:digit:]][[:digit:]])7654321

Now, it is the time to introduce &, special character.

$ echo "knowledge Must be shared" | sed 's/knowledge/(&)/'

Output:
(knowledge) Must be shared

$ echo "1234567890" |sed 's/[[:digit:]][[:digit:]][[:digit:]]/(&)/'

[OR]

If you do not want to write same thing repeatedly, we can use below syntax which is very handy and easy to use:

$ echo "1234567890" |sed 's/^[[:digit:]]\{3\}/(&)/'

[OR]

$ echo "1234567890" |sed 's/^[0-9]\{3\}/(&)/'

Output:
(123)4567890

Explanation:

& holds the value of regular expression which we are searching. 
  • When record is read and regular expression get the match, & will hold the value of matched regular expression i.e. 123
  • We have replace the matched regular expression with itself with concatenation of brackets.
Keep Reading, Keep Learning, Keep Sharing....!!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...