Please help me replace the path in multiple text files in a one-liner.

Suppose I have /home/shyam/Raghav/2014/12_dec/31122014/ in my text files and I want it to be replaced with /home/shyam/Raghav/12_dec/31122014, how can I do it?

  • To clarify, you have that string in some number of text files and want to just replace it with the shorter version? – jkeuhlen Dec 31 '14 at 5:39

In a shell

cat original_file_prefix.* | sed 's/[" ]//g' > new_file_name

Or open up your files in vim and type the following (you'll have to run it on all though)

:%s/[" ]//g

That should get rid of the quotes and spaces.


Try with this command:

sed -i 's/\/home\/shyam\/Raghav\/2014\/12_dec\/31122014\//\/home\/shyam\/Raghav\/12_dec\/31122014/g' files*

-i option edit files in place.

Replace files* with your desired search pattern.

Note that this replace /home/shyam/Raghav/2014/12_dec/31122014/ with /home/shyam/Raghav/12_dec/31122014 as you suggest. Without final / on the result. If you want it, replace /g with \//g at the end of the command.

sed -i 's:/home/shyam/Raghav/2014/12_dec/31122014/:/home/shyam/Raghav/12_dec/31122014:g' files*.txt

To change all the paths in multiple text files, I'd recommend to open all those files in a split window. i.e
'vim -o [file1] [file2] [file3] ...'
You will now see all the files are opened in a seperate ViM buffers. Now, to replace the reuired text in ALL of the buffers, you can issue:
And that should issue text substitution command in ALL of the buffers.

Your command should be then:
:windo %s/\/home\/shyam\/Raghav\/2014\/12_dec\/31122014\//\/home\/shyam\/Raghav\/12_dec\/31122014'

Hope it helps.

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.