How to search-replace contents in files in Ubuntu Linux?

My platform: Linux Ubuntu workstation

In the directory I have a series of files with the file name xxx_1.in to xxx_50.in

For each file, I want to replace abc with def. If I do this individually, I must enter: g / abc / s // def / g

How to write a script to process all files at once?

+2
source share
2 answers
sed -i 's/abc/def/g' xxx_*.in 

should be enough

+5
source

I like Python, even for shell scripts. I can't figure out how to use sed , so I stick with Python search and replace:

 #!/usr/bin/env python import os, glob for filename in glob('xxx_*.in'): os.rename(filename , filename .replace('abc', 'def')) 

So, as a built-in script that runs when you copy / paste it into Terminal (I don't have Python on my current computer, so no guarantees)

 python -c "import os, glob; eval('for f in glob(\'xxx_*.in\'):\n os.rename(filename , filename .replace(\'abc\', \'def\'))'" 

It looks like you meant the contents of the file. This, I can do without Python (hope this works):

 for f in xxx_*.in; do sed s/abc/def/g "$f"; done 
0
source

Source: https://habr.com/ru/post/1412065/


All Articles