I want to find a string in a file, do some operation and put back the string in the file. Given below is the example on what I need:
$ cat sample.txt
TimeStamp-> 123456 Name-> ABC Mail-> abc@123.com
TimeStamp-> 23456 Name-> XYZ Age-> 25
Let me modify my question. I want to read that string/number after TimeStamp->
, modify the same based on the requirement and put it back to get in the same file or create a new file. Let's say the operation is multiply by -1.
Expected output is:
TimeStamp-> -123456 Name-> ABC Mail-> abc@123.com
TimeStamp-> -23456 Name-> XYZ Age-> 25
Here a pure
bash
solution:Explanation
The
while
loop justread
each line into an array:read
options:and then uses Shell Arithmetic (
*=
) to multiply the number (an arithmetic expression) andecho
'es the modified line to newfile.txt.Thanks for all the help. It worked with while loop and sed -i. Code is as given below:
Before:
After:
Your mental model of the problem seems rather inadequate. There is a number of ways to convert a file into another file, so a traditional approach would be to produce a new file by various means, then move it on top of the original file. But for simplicity, you could use a tool which explicitly supports in-place editing, such as Perl.
This is a regular expression substitution
s/from/to/
with the/x
option to allow the replacement to be produced by another Perl expression, rather than just a string. It would not be hard to write a simple date conversion call instead of thesprintf
placeholder. The regex captures the static stringTimeStamp->
and any trailing whitespace into$1
, and the number into$2
.A somewhat more "shellish" solution would be to extract the number, run a tool or process on it, and replace the string separately. Assuming you have a
sed
which supports thei
option, and a tool calledssboetod
to calculate a replacement value, perhaps something likeWith two process substitutions, this isn't particularly elegant, though. I added this as an illustration of a typical approach more than as an actual answer.
Finally, if the input file format is under your control, I would recommend a redesign. This looks vaguely like logging data, so a semi-standard log file format would perhaps make more sense. The tagged fields, on the other hand, suggest thinking about switching to JSON for this data, although that would not simplify the handling of this particular problem.
If there is a constant number of columns in your file, and you know that the number you wish to manipulate via arithmetic is located in column 2, as it is in your sample, then you may use
awk
:Notice I multiplied column 2,
$2
, by-1
.newFile
should contain: