I have this line
UDACBG UYAZAM DJSUBU WJKMBC NTCGCH DIDEVO RHWDAS
i am trying to print the last letter of each word to make a string using awk
command
awk '{ print substr($1,6) substr($2,6) substr($3,6) substr($4,6) substr($5,6) substr($6,6) }'
In case I don't know how many characters a word contains, what is the correct command to print the last character of $column, and instead of the repeding substr
command, how can I use it only once to print specific characters in different columns
The awk variable $NF is the last field of every record; you can use it to print only the last fields of your file like so: expands to the dollar-sign followed by a number, which then expands to the value of the last field - but only because $0 is the whole line and $1 is the first word on the line.
Given string str, the task is to print the last character of each word in the string. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: Append a space i.e. ” “ at the end of the given string so that the last word in the string is also followed by a space just like all the other words in the string.
Now start traversing the string character by character, and print every character which is followed by a space. $str = $str . " "; echo($str[$i - 1] .
END {print r} prints the r variable once awk script finishes processing. In the second solution, r value is cleared upon each line processing start, and its value is printed after processing all fields in the current record.
If you have just this one single line to handle you can use
awk '{for (i=1;i<=NF;i++) r = r "" substr($i,length($i))} END{print r}' file
If you have multiple lines in the input:
awk '{r=""; for (i=1;i<=NF;i++) r = r "" substr($i,length($i)); print r}' file
Details:
{for (i=1;i<=NF;i++) r = r "" substr($i,length($i))
- iterate over all fields in the current record, i
is the field ID, $i
is the field value, and all last chars of each field (retrieved with substr($i,length($i))
) are appended to r
variableEND{print r}
prints the r
variable once awk
script finishes processing.r
value is cleared upon each line processing start, and its value is printed after processing all fields in the current record.See the online demo:
#!/bin/bash
s='UDACBG UYAZAM DJSUBU WJKMBC NTCGCH DIDEVO RHWDAS'
awk '{for (i=1;i<=NF;i++) r = r "" substr($i,length($1))} END{print r}' <<< "$s"
Output:
GMUCHOS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With