1

I have .csv file that contain 2 columns delimited with ,.

file.csv

word1,word2  
word3,word4  
word5,word6  
.  
.  
.  
.  
word1000,1001  

I want to create a new file from file.csv and insert sed command like this:

mynewfile

sed -e 's,word1,word2,gI' \  
   -e 's,word3,word4,gI' \  
   -e 's,word5,word6,gI' \  
    ....

How can I make a script to add sed command?

2 Answers 2

1

You can use sed to process each line:

echo -n 'sed ' ; sed -e "s/^\(.*\)/-e 's,\1,gl'\ \\\/" file.csv

will produce as requested

sed -e 's,word1,word2,gl' \
-e 's,word3,word4,gl' \
-e 's,word5,word6,gl' \
Sign up to request clarification or add additional context in comments.

3 Comments

I think this produces an unwanted `` on the last line.
That works thank you. One more question How can I use sed to remove the (any word) including the ( )
You should not ask questions in a comment but anyway: sed -E "s/([[:alpha:]]+)//".
1

Your goal seams to be performing custom replacements from a file. In this case, I would not generate a file containing a bash script to do the job, but I would generate a sed script to do the job:

sed -e 's/^/s,/' -e 's/$/,gI/' file.csv > sed_script
sed -f sed_script <<< "word1"

We can even avoid to use the sed_script file with bash's process substitution:

sed -f <(sed -e 's/^/s,/' -e 's/$/,gI/' file.csv) <<< "word1"

Update:

Simplifying the sed script generation, it becomes:

sed -e 's/.*/s,&,gI/' file.csv > sed_script
sed -f sed_script <<< "word1"

and

sed -f <(sed -e 's/.*/s,&,gI/' file.csv) <<< "word1"

4 Comments

sed -f <(sed -e 's/.*/s,&,gI/' file.csv) <<< "word1", Not work well. word1 separate into w o r d 1 and then go through file.csv It's look like sed w; sed o; sed r; sed d
I do not get what you mean. sed ... <<< "word1" is a shortcut for echo "word1" | sed ..., and file.csv is used to generate a sed script. So nothing go through file.csv.
Ok, This is my command echo "Test" | sed -f <(sed -e 's/.*/s,&,gI/' mydic) In mydic; test,testedd t,AlphabetT e,AlphabetE s,AlphabetS The expect result is testedd but It's be AlphabetTAlphabetEAlphabetSAlphabetT
Replacing ab by zz, a by e and b by r has a hard to predict result because your replacement overlap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.