How about:
awk -v old=$oldNum -v new=$newNum \
'{if ($1==old) {$1=new; print} else {print}}' input.txt > output.txt
Tried it like this:
$ cat input.txt
2 19/10/16 15:30 some other line
1 20/10/16 12:00 take car in the garage joe's garage
3 17/10/16 5:30 another one
$ oldNum=2
$ newNum=15
Run the awk command, then:
$ cat output.txt
15 19/10/16 15:30 some other line
1 20/10/16 12:00 take car in the garage joe's garage
3 17/10/16 5:30 another one
Is this what you wanted ? If you want your result to appear in the original file, just mv
the output file with new name input.txt
, that should overwrite the input file (use an anti-slash \mv
to avoid aliasing of the mv
command).
NOTE: you can probably obtain the same result with shorter awk instructions, but this syntax makes it more readable. sed
can probably do it in an even more concise way.
EDIT: I realise this works if you want to change only 1 number within your file. If I understand your problem correctly, you want to re-calculate the number for every line and create a file with those new numbers. The optimal way of doing that would be to include your calculation of new line number inside the awk
script, that way you don't have to create a shell loop, which is generally a bad idea since calling tools like awk
, echo
, sed
... repeatedly ends up being very costly. You could do something like this:
if [ -f $PWD/output.txt ]; then
# Remove old output if present in current directory
\rm -f $PWD/output.txt
fi
awk '{ ###calculation here, result store in newNum###; $1=newNum; print}' input.txt > output.txt
For example, if I want to trivially just increment by one every line number:
awk '{$1++; print}' input.txt > output.txt
If you cannot (or dare not) include your calculation inside awk
, you can do a loop on the file, but that's pretty clumsy from what I understand of bash
scripting:
if [ -f $PWD/output.txt ]; then
# Remove old output if present in current directory
\rm -f $PWD/output.txt
fi
while read line
do
newNum=###Calculation here for current line###
echo $line | awk -v new=$newNum '$1=new' >> output.txt
done <input.txt