awk and sed append end of line each related line

0

I want to do some line manipulation but am stuck in the line by line processing. My file looks like this:

10.10.10.10 ABtest
10.10.10.11 ABprod

I want to append a string at each line according to the string at the end of the line.

My aproach is using awk for testing against the string ABtest at the end of the line and then to convert from ABtest to test with sed. After that, I want to append the output to each related line.

I want to output as follows:

10.10.10.10 ABtest test
10.10.10.11 ABprod prod

arifisik

Posted 2019-05-25T10:46:46.970

Reputation: 160

With GNU sed: sed -E 's/(....)$/& \1/' file – Cyrus – 2019-05-25T17:57:51.083

Answers

2

There is no need for both of them, sed and awk, you can go with one tool. The code accomplishing your goal in awk could be

awk ' 
/AB/ { 
        printf $0
        gsub("^AB", "", $2)
        printf " %s\n", $2
     }
' <<EOT
10.10.10.10 ABtest
10.10.10.11 ABprod
EOT

/<expression>/ searches for regex and the {<code>} part tells awk what to do with that record. In this particular case the function gsub substitutes all appearances of 'AB' in the second column—If you want to just substitute the first appearance use sub() but regarding the regex i guess you can use either one or the other with same outcome here—and the result is printed subsequently.

It is not clear in your question if there are any lines between those to edit to be printed unaltered. If that’s the case you need to jump to the next record after match-and-edit like that:

awk '
/AB/ { printf $0; gsub("^AB", "", $2); printf " $2\n"; next; }
{ print $0 }
' <<EOT
10.10.10.10 ABtest
10.10.10.11 ABprod
testtesttets
EOT

Maybe you should create an even more specific test by using if. I strongly encourage you to take a look into some awk resources (here or here for example)

karlsebal

Posted 2019-05-25T10:46:46.970

Reputation: 183

hi karlsebal, thanks for your answer but I want to create column 3 using the information in column 2. I would like to remove the "AB" in the 2nd column of "ABtest" and "ABpord" and add the rest as the 3rd column. I don't want the 2nd column to change. I want the process done automatically in the script. I don't want to add this as static. I apologize for not explaining the question properly. – arifisik – 2019-05-25T14:49:26.757

Hi arifisik, I edited my answer accordingly. – karlsebal – 2019-05-25T15:19:11.540