Shell scripting - Modifying a files contents with sed

Discuss how to write good code, break bad code, your current pet projects, or the best way to approach novel problems

Shell scripting - Modifying a files contents with sed

Post by ampakine on Thu Jun 30, 2011 8:56 am
([msg=59227]see Shell scripting - Modifying a files contents with sed[/msg])

Lets say I want write a script that will find every occurrence of the pattern "PATTERN" in a file called "FILE". If I run this command:
Code: Select all
sed 's/PATTERN//' FILE

it will output text in which the pattern has been deleted but it doesn't actually modify the file so when I run cat FILE the pattern is still there. I tried redirecting the output to the file itself like this:
Code: Select all
sed 's/PATTERN//' FILE > FILE

but that deleted all text in the file for some reason. I can solve the problem by redirected the output to an intermediate file then outputting the intermediate files contents to the original file like this:
Code: Select all
sed 's/PATTERN//' FILE > INTERMEDIATEFILE
cat INTERMEDIATEFILE > FILE

but I'm guessing thats a completely roundabout way to do it and I wouldn't need to do that if I knew how to use the sed command properly.
ampakine
Experienced User
Experienced User
 
Posts: 65
Joined: Tue May 31, 2011 5:21 pm
Blog: View Blog (0)


Re: Shell scripting - Modifying a files contents with sed

Post by tgoe on Mon Jul 04, 2011 11:05 am
([msg=59407]see Re: Shell scripting - Modifying a files contents with sed[/msg])

AFAIK, the FreeBSD version of sed is the only one able to modify files in place. You can avoid creating the temp file by first reading all of the data into memory.

edit:
GNU sed can edit in place: -i option
User avatar
tgoe
Contributor
Contributor
 
Posts: 633
Joined: Sun Sep 28, 2008 2:33 pm
Location: q3dm7
Blog: View Blog (0)



Return to Programming

Who is online

Users browsing this forum: No registered users and 0 guests