1834089 Members
2397 Online
110063 Solutions
New Discussion

Re: Increment a # field

 
Jeff Daigle
Advisor

Increment a # field

Hello, I am trying to write a script that will open file.txt, increase a # on the first line of the file by 1, then close the file (saving it). Any ideas?
Thank you very much.
6 REPLIES 6
Vincenzo Restuccia
Honored Contributor

Re: Increment a # field

cat - << EOF | ed -s file-1
1 s/abc/#abc/
w file-1
q
EOF
A. Clay Stephenson
Acclaimed Contributor

Re: Increment a # field

Hi,

This would be my way:

F1="myfile.txt"
N=`line < ${F1}`
N2=`expr ${N} + 1`
echo "${N2}" > $F1
STAT=$?
exit ${STAT}

Regards, Clay
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Increment a # field

Hi Jeff:

Assume that in your file the second field, on the first line contains the number to be incremented. Then:

# awk '{if (NR==1){$2=$2+1};print $0}' filein > fileout

...JRF...
Jeff Daigle
Advisor

Re: Increment a # field

Thank you for the comments. Greatly appreciated. In your example, Mr. Ferguson, where does the name of my file (abc.txt) go?
Thanks again!!
James R. Ferguson
Acclaimed Contributor

Re: Increment a # field

Hi Jeff:

In the awk script I gave you, 'filein' would be replaced by your file (abc.txt). That's the input to 'awk'. The filtered file I simply called 'fileout'. In reality, you would run the 'awk' script and then overlaid 'filein' with 'fileout', like:

# awk... abc.txt > abc.new
# mv abc.new abc.txt

With my regards, Jim

...JRF...
Satish Y
Trusted Contributor

Re: Increment a # field

sed -e 's/^/#/g' file.txt > file1.txt; mv file1.txt file.txt

Cheers...
Satish.
Difference between good and the best is only a little effort