-1

I saw this question but I couldn't implement what I'm looking for.

Here is what I want:

  • I have a file with a few lines ending with 4.1.01.97 (same number for all lines - but number can change from time to time)
  • I want to open vim and change the number into another

I tried vim [file_name] +:%s/97/98/g +:wq which works fine but it wouldn't help if the file will change.

I next tried getting desired number with grep: cat [file_name] | tail -1 | grep -E '.[0-9][0-9]$'

I want to use the result of this in my vim command... Something like using vim [file_name] +:%s/97/98/g +:wq with the grep command inside ``, instead the 97.

How can I do that?

If this it possible without vim, that would also be helpful :)

Also, can my regular expression for the grep be improved?


This is how the file looks like:

A_,4.1.01.97
B_,4.1.01.97
C_,4.1.01.97
D_,4.1.01.97
E_,4.1.01.97
F_,4.1.01.97
G_,4.1.01.97
H_,4.1.01.97

This is how I want the file to look like:

A_,4.1.01.98
B_,4.1.01.98
C_,4.1.01.98
D_,4.1.01.98
E_,4.1.01.98
F_,4.1.01.98
G_,4.1.01.98
H_,4.1.01.98
1

You could use sed :

sed 's/97/98/g' /path/to/file.txt

Use sed -i to modiffy the file instead of printing to stdout:

sed -i 's/97/98/g' /path/to/file.txt

Edit:

Since you also wanted to know if your regex can be improved, here a suggestion to get the last number of the end of your lines:

tail -1  /path/to/file.txt | grep -o '[0-9]\{1,\}$'

If you want to obtain the highest integer found at the end of all lines in the file, you could:

grep -o '[0-9]\{1,\}$' /path/to/file.txt | sort -n | tail -1

You could replace it in the file as such:

sed -i 's/[0-9]\{1,\}$/<your replacement here>/g' /path/to/file.txt

Later Edit:

You may use this one liner:

pattern=`tail -1 /path/to/file.txt | grep -o '[0-9]\{1,\}$'` && sed -i "s/[0-9]\{1,\}$/${pattern}/" /path/to/file.txt
  • This is helpful but it requires me to know what is written in the file. I want to not have to write "97" but a generic line... – CIsForCookies Jan 16 '18 at 17:11
  • Gotcha! You can use the last command I added in my initial answer – AnythingIsFine Jan 16 '18 at 17:28

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.