3

I need to write a program that will read line from a file and then output the lines.

So the files contains this:

This is the first line
This is the second line
This is the third line
This was a blank line

The output should be this:

1. This is the first line
2. This is the second line
3. This is the third line
4.
5. This was a blank line

I know I can do:

nl -b a tst16

But this doesn't print the "." after the numbers plus I want to know if there is a way to do this is like a loop or something.

asked Mar 6, 2016 at 0:58
2
  • 3
    At least in the GNU coreutils version of nl, it seems to be possible to customize the separator string in the way you want e.g. (using bash) nl -b a -s $'.\t' tst16 Commented Mar 6, 2016 at 1:07
  • 1
    Try : perl -ne 'print "$.. $_"' file Commented Mar 6, 2016 at 1:09

3 Answers 3

3

Using a short while construct:

% i=1; while IFS= read -r line; do printf '%s. %s\n' "$i" "$line"; ((i++)); done <file.txt
1. This is the first line
2. This is the second line
3. This is the third line
4. 
5. This was a blank line

Expanded:

#!/usr/bin/env bash
i=1
while IFS= read -r line; do 
 printf '%s. %s\n' "$i" "$line"
 ((i++))
done <file.txt
answered Mar 6, 2016 at 1:07
0
1

You could use nl too --

nl -s". " -ba file
 1. This is the first line
 2. This is the second line
 3. This is the third line
 4. 
 5. This was a blank line
mmoya
6,3482 gold badges23 silver badges23 bronze badges
answered Mar 6, 2016 at 14:38
0

Using awk it is enough to do:

awk ' { print NR". " 1ドル } ' < file.txt

1ドル is the string of text in the input, and NR an internal awk variable that tracks the current line number (e.g. Number of Records).

8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

answered Mar 6, 2016 at 8:21

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.