awk without printing newline

前端 未结 6 1396
失恋的感觉
失恋的感觉 2020-12-12 14:24

I want the variable sum/NR to be printed side-by-side in each iteration. How do we avoid awk from printing newline in each iteration ? In my code a newline is printed by def

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 14:34

    I guess many people are entering in this question looking for a way to avoid the new line in awk. Thus, I am going to offer a solution to just that, since the answer to the specific context was already solved!

    In awk, print automatically inserts a ORS after printing. ORS stands for "output record separator" and defaults to the new line. So whenever you say print "hi" awk prints "hi" + new line.

    This can be changed in two different ways: using an empty ORS or using printf.

    Using an empty ORS

    awk -v ORS= '1' <<< "hello
    man"
    

    This returns "helloman", all together.

    The problem here is that not all awks accept setting an empty ORS, so you probably have to set another record separator.

    awk -v ORS="-" '{print ...}' file
    

    For example:

    awk -v ORS="-" '1' <<< "hello
    man"
    

    Returns "hello-man-".

    Using printf (preferable)

    While print attaches ORS after the record, printf does not. Thus, printf "hello" just prints "hello", nothing else.

    $ awk 'BEGIN{print "hello"; print "bye"}'
    hello
    bye
    $ awk 'BEGIN{printf "hello"; printf "bye"}'
    hellobye
    

    Finally, note that in general this misses a final new line, so that the shell prompt will be in the same line as the last line of the output. To clean this, use END {print ""} so a new line will be printed after all the processing.

    $ seq 5 | awk '{printf "%s", $0}'
    12345$
    #    ^ prompt here
    
    $ seq 5 | awk '{printf "%s", $0} END {print ""}'
    12345
    

提交回复
热议问题