5

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?

13

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
  • Duh, few seconds faster than me... – Byte Commander Dec 5 '16 at 13:48
  • Ok. I assume ` \ ` marks to search at the end of line or is this some escape symbol for .? What if it wasn't the end of the line? Still thanks already :) – mcExchange Dec 5 '16 at 13:51
  • @mcExchange sorry, I added explanation - it's the $ that marks the end of the line in the sed expression – Zanna Dec 5 '16 at 13:55
  • 3
    Alternatively, "s/png/mat/2" to tell sed to replace the second instance. – Maerlyn Dec 6 '16 at 9:38
  • @Maerlyn wow, TIL! – Zanna Dec 6 '16 at 10:07
7

You can replace all .png strings directly at the end of a line in INPUTFILE like this:

sed 's/\.png$/.mat/' INPUTFILE

The command above will not modify INPUTFILE but only print the changed version to the terminal.

To directly edit the file in place, add the -i flag to sed (or -i.bak to store a backup of the original file):

sed -i 's/\.png$/.mat/' INPUTFILE
  • still pretty fast :D – Zanna Dec 5 '16 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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