Home > Software engineering >  Append text in front of variable within the same line - bash
Append text in front of variable within the same line - bash

Time:04-29

I have this example.text

> cat example.text
10.10.44.11 10.10.44.20 xa1-Y xa2-Y xb1-Y xb2-Y xc1-Y xc2-Y xd1-Y xd2-Y 

and I have this command: srxa_host_list=$(echo example.text | awk '{print $3}' | sed 's/-.*//')

The Ouput:

echo $srxa_host_list
xa1

What I need: Append sr text before "xa1" without creating a new line of code.

echo $srxa_host_list
srxa1

CodePudding user response:

1st solution: With your shown samples, please try following awk program. We can do all this with a single awk program.

awk -F'[ -]' '{print "sr"$3}'  Input_file

Explanation: Simple explanation would be, setting field separator as space and - for all the lines. In main program printing sr string followed by 3rd field of current line, as per shown output.



2nd solution: Using sub method of awk program try following program.

awk '{sub(/-.*/,"");print "sr"$3}' Input_file

Explanation: using sub function to substitute from 1st occurrence of - till last of the line with NULL then printing str string followed by 3rd field.



3rd solution: Using sed with -E(enabling ERE) option please try following program.

sed -E 's/^[^ ]*  [^ ]*  ([^-]*)-.*/sr\1/' Input_file

Explanation: using sed's -E option to enable ERE(extended regular expression). Then in main program matching from starting ^[^ ]* [^ ]* followed by a capturing group where matching everything before - followed by -.* and substituting it with sr and 1st capturing group.

CodePudding user response:

Using sed

$ srxa_host_list="sr$(sed 's/[^-]* \([^-]*\).*/\1/' example.text)"
$ echo "$srxa_host_list"
srxa1
  • Related