Search code examples
awksedcuttr

Reprint column with modifications


I have a file that looks like this:

lbsrv_standards-d
lbsrv_standards-t
lbsrv_standards

Desired output:

rename lbsrv_standards-d lb_standards-d
rename lbsrv_standards-t lb_standards-t
rename lbsrv_standards lb_standards

So I need to print $1, a space and then print a modified version of $1, I've been using awk but I can't figure out the substitution without adding a newline between the original and modified $1s.

Solution:

awk '{print "rename "$1} ; { gsub("lbsrv", "lb", $1) ; print }'

Output:

rename lbsrv_standards-d 
lb_standards-d
rename lbsrv_standards-t 
lb_standards-t
rename lbsrv_standards 
lb_standards

Any assistance would be appreciated

Thanks


Solution

  • You may use

    awk  '{a=$0; sub(/^lbsrv/, "lb", a); print "rename "$0" "a }'
    

    See the online demo

    Details

    • a=$0 - a temporary variable is declarted with the value of the whole line
    • sub(/^lbsrv/, "lb", a) - the lbsrv at the start of the string is replaced with lb
    • print "rename "$0" "a - prints the result: rename, space, the whole line, space and then the contents of the a variable.

    A simpler solution is possible with sed (especially if the strings come in individually):

    sed 's~^lbsrv\(.*\)~& lb\1~' file > newfile
    

    See this sed demo

    This is a BRE POSIX pattern based sed command that finds

    • ^ - start of a line
    • lbsrv - substring
    • \(.*\) - Group 1: any 0 or more chars up to the end of the line/input.

    The & lb\1 is a replacement pattern that takes the whole line first, then appends a space, lb and then the contents of Group 1.