9

I want to print out a file that has 1 column listing values like:

cat
dog
house

But I want to have the file print like this to another file:

1 cat
2 dog
3 house

I think that awk could be used to do this?

Can you provide the command to do that? I know I need to do something like this to print the file:

awk -F '{ print $1 }'

But would I do something like this:

int i
awk -F '{ print i, " " $1 }'
i++

(Left my awk book at work)

1
  • 3
    cat -n would do this job. Commented Dec 5, 2015 at 16:14

2 Answers 2

10

This can be done with NR (Number of Records):

awk '{ print NR, $1 }'

Example:

$ echo -e "test test\ntest test" | awk -F'\n' '{print NR, $1}'
1 test test
2 test test
5
  • I'm looking to see how to get it to read multiple lines, the way i did it, I only get one line. Can you suggest else I need to do to get all the lines of the file? cat object_list.tsv |awk '{ print NR, $1 }'. Perhaps it is because it is a tab separated file.
    – Jazzmine
    Commented Dec 5, 2015 at 16:31
  • If it's tab separated, try using -F'\t' for it to split at the tabs.
    – Sly
    Commented Dec 5, 2015 at 16:37
  • do you have to use non-standard prompts here? especially one that looks like a bolded redirection operator? I'm sure you think it looks pretty but please stick to the convention of $ for non-root prompt, # for root prompt, and % for csh.
    – cas
    Commented Dec 5, 2015 at 23:08
  • @cas Forgot to change it.
    – Sly
    Commented Dec 5, 2015 at 23:33
  • 2
    If you just want to keep the whole input line, don't bother with -F and do awk '{print NR,$0}' Commented Dec 6, 2015 at 2:34
-1

You can use rows and columns restrictions, for instance:

I'd like to show the %idle average of cpu, like the picture:

iostat

so, you can use the command:

 iostat | awk 'NR==4{print $6}'

Result: iostat | awk 'NR==4{print $6}'

1
  • 2
    Welcome to the site, and thank you for your contribution. Please note however that the OP is not asking how to print a specific column of a given line, but how to prefix the output of a given column with the line number.
    – AdminBee
    Commented Jun 24, 2021 at 13:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .