2

I am reviewing an existing script using sed commands in cshell, and I understand all of it except one component. I have simplified it down for sharing an example but below, $templateFile is used as input, and all instances of "hello" are replaced with "world", and once this is done, it is output to the output directory and named with the output file name.

sed -e 's:hello:world:g' <"$templateFile"> "$outputDir"/"$outputFileName".txt

However, I don't understand what the <> around "$templateFile" is doing? Why is it necessary to have the <> for a sed input file? In all descriptions of sed, I can't find an explanation for what purpose this might be serving so I am a bit confused.

I understand this is a simple question, but I cannot find an answer online and I'd appreciate any clarification here. Thank you.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
JE52
  • 201
  • 2
  • 7

2 Answers2

1

The code you're reviewing has misleading use of whitespace. A more readable version might look like:

sed -e 's:hello:world:g' <"$templateFile" >"$outputDir/$outputFileName.txt"

As usual, <infile redirects stdin from infile, and >outfile redirects stdout to outfile.

Like other redirections, all this happens before sed is even started; sed itself has no bearing on or control over how the shell interprets these parts of the command.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
1

The < and > are stream redirection operators.

You do not need the < operator because sed accepts a filename argument after the sed command.

If you plan to save sed replacement result in a new file, > is required. If you want to save the file contents "inline", there is no obligation to use > either. With GNU sed, you can do

sed -i 's:hello:world:g' "$templateFile"

With Free BSD sed, you can do

sed -i '' 's:hello:world:g' "$templateFile"

Check the sed edit file in place question.

You do not need -e either, it only signals that the next argument is the sed command.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
  • @MartinTournoij That is why I specifically used the `GNU` and `Free BSD` terms in my answer. – Ryszard Czech Jan 07 '21 at 20:50
  • 1
    Sorry about that-- couldn't decide who to accept between you and Charles Duffy as you were both helpful but I'll do it now. – JE52 Jan 07 '21 at 22:34
  • @JElder At least you helped me with my rep :) Charles has got [a lot](https://stackoverflow.com/users/14122/charles-duffy) of points already. And more rep means more features are available for you. – Ryszard Czech Jan 07 '21 at 22:43
  • Oops, sorry; I missed that part somehow How silly of me. – Martin Tournoij Jan 08 '21 at 11:20