3

I have two scripted files, say file1 and file2. I want to take the content of file1, change character a to A in file1 and append the output to file2 without modifying the content of file1. I'm trying with:

sed -i ‘s/a/A/g’ file1 >> file2

but this just changes the a to A in file1.

BeastOfCaerbannog
  • 12,964
  • 10
  • 49
  • 77
Radagast
  • 33
  • 2
  • the opposite of this: [Sed command in Ubuntu not working](https://askubuntu.com/questions/765019/sed-command-in-ubuntu-not-working) – steeldriver Sep 03 '22 at 17:44
  • ... fyi sed has a `y` command that is more idiomatic for single character replacements: `sed 'y/a/A/' file1 >> file2` – steeldriver Sep 03 '22 at 17:45
  • @steeldriver Does using `y` pose an advantage to using the `s` command? – BeastOfCaerbannog Sep 03 '22 at 17:56
  • 1
    @BeastOfCaerbannog I don't know tbh - in theory it could be more efficient since it doesn't need to invoke a regular expression engine, but whether it's actually implemented more efficiently is a different matter. Probably the OP should be using `tr` rather than `sed` in this application. – steeldriver Sep 03 '22 at 18:18

1 Answers1

4

Just remove the -i flag:

sed 's/a/A/g' file1 >> file2

The -i flag is used to edit the specified file in place, so it does just that to file1. From man sed:

-i[SUFFIX], --in-place[=SUFFIX]

       edit files in place (makes backup if SUFFIX supplied)

The reason you get nothing appended to file2 when you use -i is that >> is used to append stdout to the specified file. But since file1 is edited in place due to -i, no output is generated, so nothing is appended to file2.

BeastOfCaerbannog
  • 12,964
  • 10
  • 49
  • 77