1

This works if I don't use variables. I don't understand why it won't work when I place variables inside. Can anyone help? The variables contain a path to a file.

sed s/$old/$new/ Current_series_list.txt"
beroe
  • 11,784
  • 5
  • 34
  • 79
  • possible duplicate of [About replacing string with sed](http://stackoverflow.com/questions/7976975/about-replacing-string-with-sed) – tripleee Oct 05 '13 at 18:05

2 Answers2

3

Paths may contain forward slashes. Use a different character for separating the command arguments, such as #:

sed "s#$old#$new#" Current_series_list.txt

Of course, this is still fragile due to regex metacharacters. Consider using the following instead:

ruby -e '$stdin.each_line { |l| puts l.sub(ARGV[0], ARGV[1]) }' \
     "$old" "$new" < Current_series_list.txt

A more portable equivalent in Perl is left as an exercise for the reader.

  • Thanks, can I send the result bach to the same file with – user2764736 Oct 05 '13 at 18:41
  • Use `sed -i` for in-place editing. No, you cannot use redirection (easily) to read and write a file at the same time; and certainly, input redirection is not the right tool here. – tripleee Oct 05 '13 at 18:58
  • @user2764736 [sponge(1)](http://linux.die.net/man/1/sponge) should be useful here. Append `| sponge Current_series_list.txt` to the command. –  Oct 05 '13 at 19:06
  • perl -e '($o,$n)=@ARGV;while(){s/$o/$n/;print}' "$old" "$new" < Current_series_list.txt – Nahuel Fouilleul Oct 05 '13 at 19:31
0

What is the value of old and new? If they contain slashes, then they will expand the sed pattern to something that isn't valid. Your trailing quotation mark probably is also not helping.

Shaggy Frog
  • 27,575
  • 16
  • 91
  • 128