awk substr several times in a row
Solution 1
This is one of the solutions to such a problem (messy but works).
echo qwertyuiop | awk '{m=substr($1, 6, 4); {while (count++<3) string=string m;
print substr($1, 1, 3) string}}'
qweyuioyuioyuio
Solution 2
Yes. You can simply save the substring to a variable, then re-print it as needed. Don't forget to set a null OFS
:
awk '{ print substr($1, 1, 3), x = (substr($1, 6, 4)), x, x }' OFS=
Testing:
echo "qwertyuiop" | awk '{ print substr($1, 1, 3), x = (substr($1, 6, 4)), x, x }' OFS=
Results:
qweyuioyuioyuio
If you need to print something more than three or four times, it may be worthwhile using a for
loop:
echo "qwertyuiop" | awk '{ for(i=1;i<=5;i++) x = x substr($1, 6, 4); print substr($1, 1, 3), x }' OFS=
Results:
qweyuioyuioyuioyuioyuio
Solution 3
There is a delightful post explaining various ways of repeating string in awk.
I'll quote the most obvious:
function rep1(s,n, r) {
# O(n) allocate/appends
# 2 lines of code
# This is the simplest possible solution that will work:
# just repeatedly append the input string onto the value
# that will be passed back, decrementing the input count
# until it reaches zero.
while (n-->0) r = r s;
return r;
}
PS: The large amount of space before function parameter in awk
indicates that this parameter is used as temporary local variable.
pogibas
Mottos and work principles: Good is good, but better is better Don't do invisible job Early is on time, on time is late, and late is unforgivable Swallow a toad Hope for the best, plan for the worst Insights are more useful than details Communication is the key / Never be afraid to ask for help Interests: Shotokan karate Learning languages (I don't know many, but this is my goal) Poetry
Updated on June 04, 2022Comments
-
pogibas almost 2 years
I am using
awk substr()
to extract a sub string from the string.For example if my string looks like this:
qwertyuiop
And I want to extract (1-3) & (6-9) characters I use this:
awk '{print (substr($1, 1, 3) substr($1, 6, 4))}' qweyui
How can I repeat a specific subtraction several times?
For example, I want to extract (1-3) & (6-9)(6-9)(6-9) characters to get the result like ths:
qweyuioyuioyuio
Of course I can use a command like this:
awk '{print (substr($1, 1, 3) substr($1, 6, 4) substr($1, 6, 4) substr($1, 6, 4))}'
Is there a simpler way?