Ubuntu – Replace second instance of string in a line in an ASCII file using Bash

bashcommand linesedtext processing

I have an ASCII file with the following structure:

file1.png otherfile1.png
file2.png otherfile2.png
file3.png otherfile3.png
...

I want to replace .png with .mat, but only for the second column. The result should be like this:

file1.png otherfile1.mat
file2.png otherfile2.mat
file3.png otherfile3.mat
...

How do I do that in Bash?

Best Answer

Well, if it is the end of the line...

$ sed 's/\.png$/.mat/' file
file1.png otherfile1.mat
file2.png otherfile2.mat
file3.png otherfile3.mat
  • s/old/new/ search and replace
  • \. literal dot (without the escape it matches any character)
  • $ end of line

Or to explicitly specify the second column, you could use an awk way...

$ awk 'gsub(".png", ".mat", $2)' file
file1.png otherfile1.mat
file2.png otherfile2.mat
file3.png otherfile3.mat
  • gsub(old, new, where) search and replace
  • $2 second column