Shell – replace ‘_’ with ‘,’ in a file which contains list of filenames

awkshellshell-scripttext processing

It will be helpful for me if someone could help to write a shell script to meet the following requirement.

I have a text file which contains list of filenames as shown below:

ADB_AR_2006_07.pdf
ADBL_AR_2010_11.pdf
CBL_AR_2013_14.pdf
CZBIL_AR_2007_08.pdf
BOKL_AR_2015_16.pdf
..
..

Now I want to replace the first and second '_' with ',' for all the filenames listed in the text file.So that the filenames become:

ADB,AR,2006_07.pdf
ADBL,AR,2010_11.pdf
CBL,AR,2013_14.pdf
CZBIL,AR,2007_08.pdf
BOKL,AR,2015_16.pdf
..
..

Best Answer

You could use a simple sed expression:

sed -Ei 's/^([^_]+)_([^_]+)_/\1,\2,/' file

file contents after modification:

ADB,AR,2006_07.pdf
ADBL,AR,2010_11.pdf
CBL,AR,2013_14.pdf
CZBIL,AR,2007_08.pdf
BOKL,AR,2015_16.pdf

  • i - allows in-place file modification

  • -E - allows extended regular expressions


A simplified approach would look as:

sed -i 's/_/,/; s/_/,/' file
Related Question