I want to do some line manipulation but am stuck in the line by line processing. My file looks like this: ABtest 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: ABtest test ABprod prod
  • With GNU sed: sed -E 's/(....)$/& \1/' file – Cyrus May 25 at 17:57

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 ABtest ABprod

/<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 ABtest ABprod

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)

  • 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 May 25 at 14:49
  • Hi arifisik, I edited my answer accordingly. – karlsebal May 25 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.