Friday, April 29, 2022

[SOLVED] How to add header to a file using sed command in python

Issue

I'm trying to add the following line to the beginning of file using sed command in python:

ID|SEC_NO|SEC_CD|SEC_DATE|SEC_ID1|SEC_DESC1|SEC_ID2|SEC_DESC2|SEC_ID3|SEC_DESC3

Command: sed -i '1i ID|SEC_NO|SEC_CD|SEC_DATE|SEC_ID1|SEC_DESC1|SEC_ID2|SEC_DESC2|SEC_ID3|SEC_DESC3' file.csv

The above command is working fine from bash. But when i am trying to run the same command from python I am getting error.

cmd =["sed", "-i", "'1i ID|SEC_NO|SEC_CD|SEC_DATE|SEC_ID1|SEC_DESC1|SEC_ID2|SEC_DESC2|SEC_ID3|SEC_DESC3'", "file.csv"]

i got this error message

"sed: -e expression #1, char 1:unkown command: `''\n"

Please assist


Solution

Single quotes ('s) are interpreted by shell to treat the enclosed sequence of characters as one argument to the command. When you run a command along with its arguments as a list with subprocess.run in Python, each list item would be passed to the command as-is as an argument, so you should not use single quotes to enclose any of the arguments:

cmd = ["sed", "-i", "1i ID|SEC_NO|SEC_CD|SEC_DATE|SEC_ID1|SEC_DESC1|SEC_ID2|SEC_DESC2|SEC_ID3|SEC_DESC3", "file.csv"]

Otherwise the single quotes themselves would be part of the arguments, which in your case get interpreted by sed.



Answered By - blhsing
Answer Checked By - Pedro (WPSolving Volunteer)