0

I'm trying to number each line of a file with this format: /1/,/2/,...

For example

From

UK
Australia
Newzealand
Brazil
America

To

/1/ UK
/2/ Australia
/3/ Newzealand
/4/ Brazil
/5/ America

I think about

grep -n file.txt // but the format is 1: , 2: , ...
nl file.txt  // but the format is 1 , 2 , 3

Can i give a specific format to nl command?

Inian
  • 62,560
  • 7
  • 92
  • 110
Francis Ngueukam
  • 894
  • 1
  • 8
  • 24

2 Answers2

4

Use the printf function in Awk, with the characters / around the integer part.

awk '{printf("/%d/ %s\n", NR, $0)}' file
/1/ UK
/2/ Australia
/3/ Newzealand
/4/ Brazil
/5/ America

NR is a special variable in awk which tracks the record number of each line as it is processed, and the line as such being $0. The above command is POSIX compatible since awk in all major platforms support printf with format specifiers.

A proper way to do it in bash alone, without any third-party tools.

#!/bin/bash

count=1
while IFS= read -r line
do
  printf "/%d/ %s\n" "$count" "$line"
  ((count++))
done <input-file

AFAIK, from the man nl page, there are options you can use, but NONE to wrap the line numbers around the characters you want, you can of-course use it one side, with -s flag

The closest I could do with it is,

nl -nrz -s/ -w1 file
1/UK
2/Australia
3/Newzealand
4/Brazil
5/America

here, -nrz for right justification and -s for the special character to use after the numbering done. In this case, I have a added a / and -w controls the width of the numbering part.

Inian
  • 62,560
  • 7
  • 92
  • 110
2

With GNU cat and GNU sed:

cat -n file | sed 's|^ *|/|;s|\t|/ |'

Output:

/1/ UK
/2/ Australia
/3/ Newzealand
/4/ Brazil
/5/ America

I used two s commands with this format: s|regexp|replacement|.

s|^ *|/|: This replaces in a line starting (^) with zero or more (*) blanks by a /

s|\t|/ |: This Replaces a tab (\t) by a slash followed by a blank.


See: The Stack Overflow Regular Expressions FAQ

Community
  • 1
  • 1
Cyrus
  • 69,405
  • 13
  • 65
  • 117