'Append text in front of variable within the same line - bash
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
Solution 1:[1]
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.
Solution 2:[2]
Using sed
$ srxa_host_list="sr$(sed 's/[^-]* \([^-]*\).*/\1/' example.text)"
$ echo "$srxa_host_list"
srxa1
Solution 3:[3]
If you need the value of the 3rd field keeping the default field separator, you can also split on - and append the first part to sr
awk '{split($3, a, "-");print "sr"a[1]}' example.text
Output
srxa1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | HatLess |
| Solution 3 | The fourth bird |
