Skip to main content
6 of 6
Use only the `y` command
xhienne
  • 18.3k
  • 2
  • 58
  • 71

Changing characters

Changing a set of characters to another set of characters is generally a task for the tr command but since you want to do it on certain lines only, it will be best done by sed which has a y command similar to tr:

sed -e "/^KEYWORD_1/  y/\"/'/" \
    -e "/^KEYWORD_2/  y/'/\"/" \
    file

Each sed command here starts with a line selector /^KEYWORD/ which instructs sed to only operate on the line matching the pattern between /. Here the patterns start with the character ^ to indicate they are to be found at the beginning of the line.

Following the line selector is sed's substitution command y/set1/set2/g which replaces every occurrence of a character in set1 with the character which has the same position in set2.

Swapping characters

Now, if on the same line you want to replace each " with ' and at the same time each ' with ", you can use only one command:

sed -e "/^KEYWORD_1\|^KEYWORD_2/  y/\"'/'\"/" file
xhienne
  • 18.3k
  • 2
  • 58
  • 71