1748165 Members
3850 Online
108758 Solutions
New Discussion юеВ

hp textfile adding index

 
SOLVED
Go to solution
Ferdi Castro
Advisor

hp textfile adding index

Hi Everyone,

Can you help me here.
I have a file having contents below
asdf
qwer
asff
and i want to add an index prompting what control number will I start so if i say 1 it will change output to

asdf 1
qwer 2
asff 3

so if i say start number is 125 it will have output like

asdf 125
qwer 126
asff 127

so that it automatically increases by one for each entry. I will be glad if you can help me using this with awk. thanks much.
6 REPLIES 6
Indira Aramandla
Honored Contributor

Re: hp textfile adding index

Hi Ferdi,

Try this

cat file.text |awk '{print $1 " " a+1; a++}'
asf 1
bfc 2
edr 3
wes 4



cat file.text |awk '{print $1 " " a+120; a++}'

asf 120
bfc 121
edr 122
wes 123


Indira A
Never give up, Keep Trying
Frank de Vries
Respected Contributor

Re: hp textfile adding index

With awk would be nice,
but a quick solution would be something like this:

#/sbin/sh
# script with passing parameter
typeset -i VAR
VAR=$1
cat yourfile |while read LINE
do
print "$LINE $VAR"
VAR=(($VAR + 1))
done

For a prompt you can add a read VAR

#/sbin/sh
# script with prompt

print "Type your control nr. here:\n"
typeset -i VAR
read VAR

cat yourfile |while read LINE
do
print "$LINE $VAR"
VAR=(($VAR + 1))
done

Many variations are possible,
but is the basic skeleton.

Look before you leap
Ferdi Castro
Advisor

Re: hp textfile adding index

Thanks Indira. I find your solution better however I need it it to be prompted in a script
I tried ff same but it give me error?

echo "enter start index \c"
read index

cat file | awk '{print $1 | $index+1;$index++}'

returns an error

awk: Field $() is not correct.
The input line number is 1.
The source line number is 1.

pls help


gives an error. Im pretty sure Im close its just that I need to get the clear use of variable.
Steve Steel
Honored Contributor
Solution

Re: hp textfile adding index

Hi

echo "enter start index \c"
read index
cat $file |awk -v a=$index '{print $1 " " a; a++}'



Steve Steel
If you want truly to understand something, try to change it. (Kurt Lewin)
Indira Aramandla
Honored Contributor

Re: hp textfile adding index

Hi Ferdi,

awk dies not understand the $varibale as it is form the shell. May be use awk -v

I think if you need to be prompted for the index number then do as a script.


IA

Never give up, Keep Trying
Arturo Galbiati
Esteemed Contributor

Re: hp textfile adding index

hi,
using awk only (not cat is needed):

read b?"Start index "
awk 'BEGIN {B='''$b'''};{print $0 " " B++}' file

code in the BEGIN step assign to the AWK var B teh value of UNIX var b.
Rest of te code print the record in teh file plus the counter.

HTH,
Art