0

I have this line of output:

M file.txt

Getting fed into this awk program:

awk '{printf("\t%s: %s %s\n", FNR, $1, $2)}'

which returns

1: M file.txt

This works and is the usual case. However, if the file has spaces and the line of output looks something like this:

M "tmux split-window subcommand.md"

awk gives give this:

1: M "tmux

But the desired output is this:

1: M "tmux split-window subcommand.md"

How can I fix this?

  • 1
    What's your end goal here? if you just want to number your output lines, piping to nl or cat -n would be simpler. If you insist on using awk, you could print the whole record e.g. '{printf("\t%s: %s\n", FNR, $0)}' – steeldriver Apr 17 at 1:44
0

If you use a delimiter, it will not consider the spaces in between your quotations as separate words.

So we can use any delimiter that you feel will not show up in your input string.

echo 'M "tmux split-window subcommand.md"' | awk -F: '{printf("\t%s: %s %s\n", FNR, $1, $2)}' 1: M "tmux split-window subcommand.md"

  • 2
    This seems to be just an obfuscated way of printing $0 (since if the record doesn't contain the chosen delimiter, $1 equals $0 and $2 is empty) – steeldriver Apr 17 at 2:24
2

To prepend the line number to the current line using awk:

awk '{ printf("%d: %s\n", FNR, $0) }'

The zeroth field, $0, is the complete line.

0

try this:

  #!/usr/bin/awk -f
  BEGIN {
        #FPAT = "([^,]+)|(\"[^\"]+\")" # seperator is ,
        #FPAT = "([^,]*)|(\"[^\"]*\")" # seperator is , and allow empty field -> notice the "+" changed to "*"
        FPAT = "([^ ]+)|(\"[^\"]*\")" # seperator is <space> -> notice the "," changed to " "
  }
  {
    printf("%d: ", FNR);
        for (i = 1; i <= NF; i++) {
            printf("%s ", $i)
        }
    printf("\n");
  }

I got it from GNU awk's online manual. Here is it. https://www.gnu.org/software/gawk/manual/html_node/Splitting-By-Content.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.