2

In a shell script, is there a way to ONLY re-number the list, but not the contents in the list? For example:

3. cat
1. hat
2. mouse

and change it to:

1. cat
2. hat
3. mouse

Thank you.

4
  • 1
    Your question doesn't seem to be related to Kali Linux, but it is probably a general Linux/Unix shell scripting question. But your question is not clear. Do you have a file that contains the data shown in the question and you want to create the expected output? Commented Sep 20, 2019 at 15:22
  • 4
    Maybe awk '{ $1=NR "."; print }' Commented Sep 20, 2019 at 15:24
  • 1
    Not maybe @Bodo. This should be the answer! Commented Sep 20, 2019 at 15:47
  • @Bodo, yeah you're right. I labeled it wrong. My brain was fried trying to figure out how to do this haha. Commented Sep 20, 2019 at 20:49

2 Answers 2

6

Simply:

awk '$1=NR "."'

This will change the first field (first text before a blank space) to the line (record) number and a dot. Since the record number is always positive and greater than 0, the result of the assignment will always be true causing the line (record) to be printed with the first field changed.

As the first field gets changed the NF (number of fields) and the zero field ($0) get re-calculated transforming all repeated white-space to one space.

That is: lines that have multiple adjacent spaces (and tabs) are coalesced into a single space.

If multiple spaces need to be salvaged from awk processing, it becomes quite more convoluted (only GNU awk has patsplit):

awk '{
       n=patsplit($0,f,/[^ \t\n]+/,s);   # split the line storing whitespace.
       f[1] = NR "."                     # only change actually needed.
       for(i=0;i<=n;i++)                 # for all fields (and separators)
       {  
          printf("%s%s",f[i],s[i])       # print each field and separator.
       }
       print("")                         # cause the printing of an OFS
     }
    ' patsplitfile
0
1
cut -d. -f2- input | nl -ba -w 1 -s .

This strips the leading numbers and period from the input then pipes it to nl, which is instructed to:

  • -ba -- number every line
  • -w 1 -- use one column for the inserted numbers
  • -s . -- use . as the separator between the inserted numbers and the text

On a sample input of:

3. cat
4. some words
1. hat
2. mouse
10. house
9. box
8. fox
7. here
6. there
5. anywhere

The output is:

1. cat
2. some words
3. hat
4. mouse
5. house
6. box
7. fox
8. here
9. there
10. anywhere

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.