Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sed read its script from a file?

Tags:

unix

sed

Recently I came across following grep command:

/usr/xpg4/bin/grep -Ff grep.txt input.txt > output.txt 

which as per my understanding means that from input.txt, grep the matter contained in grep.txt and output it to output.txt.

I want to do something similar for sed i.e. I want to keep the sed commands in a separate file (say sed.txt) and want to apply them on input file (say input.txt) and create a output file (say output.txt).

I tried following:

/usr/xpg4/bin/sed -f sed.txt input.txt > output.txt 

It does not work and I get the following error:

sed: command garbled 

The contents of files mentioned above are as below:

sed.txt

sed s/234/acn/ input.txt sed s/78gt/hit/ input.txt 

input.txt

234GH 5234BTW 89er 678tfg 234 234YT tfg456 wert 78gt gh23444 
like image 669
sachin Avatar asked Oct 27 '10 08:10

sachin


People also ask

How do you sed a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Can sed read from stdin?

The sed command can read and process text from input files or standard input streams. Since our text is not saved in a file, if we can somehow write the text to stdin, then sed can read it.

What is script format in sed?

To use sed, you write a script that contains a series of editing actions and then you run the script on an input file. Sed allows you to take what would be a hands-on procedure in an editor such as vi and transform it into a look-no-hands procedure that is executed from a script.


2 Answers

Your sed.txt should only contain sed commands: No prefixing with sed or suffixing with an input file. In your case it should probably be:

# sed.txt s/234/acn/ s/78gt/hit/ 

When ran on your input:

$ /usr/xpg4/bin/sed -f sed.txt input.txt 
 acnGH 5acnBTW 89er 678tfg acn acnYT tfg456 wert hit ghacn44 
like image 53
schot Avatar answered Oct 05 '22 17:10

schot


Rather than keeping the sed commands in a separate text file, you may want to try creating a sed script. The file below can run directly on your data files:

./myscript.sed inputfile.txt > outputfile.txt

#!/bin/sed -f s/234/acn/ s/78gt/hit/ 
like image 43
Kevin Avatar answered Oct 05 '22 17:10

Kevin