bash leaning on TR to format anwsers

I have a really bad habit of abusing tr. I need to find another way, a different style. all I want to so is print the list horizontally instead of vertically - so I can cut and past it into an email. Check out the use of the TR command. Just terrible.

$ cat /tmp/wig
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'monohajoxx' where user_name = 'monohajo'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'wuemxx' where user_name = 'wuem'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'taraziemxx' where user_name = 'taraziem'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'mullankexx' where user_name = 'mullanke'
update PTMM_ARCHIVE.FASTTRACK_USER set user_name = 'fernanjaxx' where user_name = 'fernanja'
$ awk '{print $NF}' /tmp/wig | tr -d "'" | tr "\n" ", \s" ; echo  "\n"
monohajo,wuem,taraziem,mullanke,fernanja,\n

Answers


Using awk

Here is one way to do it entirely with awk:

$ awk '{gsub(/'\''/,"",$NF); printf "%s%s",(NR>1?",":""),$NF} END{print "\\n"}' wig
monohajo,wuem,taraziem,mullanke,fernanja\n

The gsub command removes the single-quotes from the last field. The printf command prints the last field preceded by a comma if this isn't the first line. The final print statement finishes the line.

And, here is another:

$ awk '{printf "%s%s",(NR>1?",":""),substr($NF,2,length($NF)-2)} END{print "\\n"}' wig
monohajo,wuem,taraziem,mullanke,fernanja\n

This uses a similar printf statement but uses substr to remove the first and last characters of the last field.

Using sed
$ sed -nE "s/.*'([^']*)'/\1/"'; H; 1h; ${x; s/\n/,/g; s/$/\\n/; p}' wig
monohajo,wuem,taraziem,mullanke,fernanja\n

How it works:

  • -n tells sed not to print anything unless we explicitly ask it to.

  • -E tells sed to use extended regular expressions so that we don't have to type as many backslashes.

  • s/.*'([^']*)'/\1/

    This removes everything from the line except for the last field single-quoted string (with the quotes are removed).

  • H; 1h;

    H adds a newline to the hold space followed by a copy of the current pattern space (which now contains the last field, minus the quotes).

    If this is the first line, however, the h command overwrites the hold space with just the current value of the pattern space (no newline).

  • ${x; s/\n/,/g; s/$/\\n/; p}

    On the last line, denoted by $, this does the following:

    - `x` exchanges the hold and pattern spaces.
    
    - `s/\n/,/g` converts all those newlines to commas.
    
    - `s/$/\\n/` puts a `\n` at the end.
    
    - `p` causes this pattern space to be printed.
    

Need Your Help