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)
sed -E 's/(....)$/& \1/' file
– Cyrus May 25 at 17:57