Reverse a word or string in a line in a file

Viewed 43

I have a file with different data where everyline consists of date in yyyyMMdd format I need the same file but that particular date need to be changed like ddMMyyyy.

Example.

Data is as below

Neeraj hyderbad     20221017
Pavan. Secunderabad 20220911

Data needed as below

Neeraj hyderbad.    17102022
Pavan. Secunderabad 11092022

The date starts exactly at same place every line like fixed length is the file format. Please suggest me the ans using awk command or python .

1 Answers

You can try this


with open('input_file.txt', 'r') as f:
    with open('output_file.txt', 'w') as f1:
        for line in f:
            line = line.split()
            line[-1] = datetime.datetime.strptime(line[-1], "%Y%m%d").strftime("%d%m%Y")
            line = ' '.join(line) + '\n'
            f1.write(line)
Related