2

I have this file

10.1.1.1    www1           
10.1.1.2    www2           
10.1.1.3    www3            

I want to extract first IP address field and move it following place with http://www.foo.com=10.1.1.1/test.php

10.1.1.1    www1           # http://www.foo.com=10.1.1.1/test.php
10.1.1.2    www2           # http://www.foo.com=10.1.1.2/test.php
10.1.1.3    www3           # http://www.foo.com=10.1.1.3/test.php

I can do this with for loop but i want to do it with sed with single liner trick.

2 Answers 2

5
sed 's@\([^ ]*\)\(.*\)@\1\2 #http://www.foo.com=\1/test.php@'
  • I used @ as the delimiter not to have to backslash the slashes in the address.

  • The IP address is matched by [^ ]*, i.e. non-whitespace at least zero times, and captured by \(\) into \1. The rest of the line is captured into \2 by .*, i.e. anything.

2
  • 1
    Slightly shorter: sed 's@\([^ ]*\).*@& #http://www.foo.com=\1/test.php@'
    – janos
    Dec 16, 2017 at 20:36
  • +1 since the question refers sed and this is a sed solution indeed Dec 16, 2017 at 22:02
4

a one line awk approach: (I'll delete if you really don't want awk)

Thanks to RomanPerekhrest for the improvement:

awk '{ $3="# http://www.foo.com="$1"/test.php" }1' $file

Or if you want/need to keep the tabs in your output:

awk 'BEGIN{OFS="\t";}{ $3="# http://www.foo.com="$1"/test.php" }1' $file
5
  • awesomenesssss!!!! awk is amazing too! good to learn
    – Satish
    Dec 16, 2017 at 19:45
  • 4
    even shorter awk '{ $3="# http://www.foo.com="$1"/test.php" }1' file Dec 16, 2017 at 19:46
  • I would ANSWER this because you were first, also i like this new awk one liner :)
    – Satish
    Dec 16, 2017 at 19:52
  • I think choroba should have gotten the answer. He actually answered before me and he used sed as you had asked.
    – jesse_b
    Dec 16, 2017 at 20:15
  • I listen to you 🙂
    – Satish
    Dec 19, 2017 at 23:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .