0

I have a large (>1000 line) file consisting of two columns, and I need to process other files to change occurrences in the first column to that of the second column.

Is there a way to get sed to automatically run through each element in the first column and change them to the second, without manually typing out a sed command with s/../../g for each one of the synonyms table?

I could loop through each line in the synonyms table and automatically populate a sed command per (synonyms) line per file, but this is possibly inefficient.

Inian
  • 80,270
  • 14
  • 142
  • 161
user36196
  • 133
  • 11
  • 1
    This is rather unclear. Can you show an example? You can easily change the entire file into a `sed` script to do what you want, but perhaps there is a simpler solution. `sed 's/column1\tcolumn2/s%^column1\t%column2\t%/'` and etc – tripleee Mar 25 '19 at 11:31

1 Answers1

1

If you are looking to parse column wise content with a known column separator, using awk is much more efficient. For your requirement I think

awk '{ $1 = $2 }1' file

is all you need. This is assuming the columns are separated by one more set of white-spaces. Use a temporary file for your redirection if your Awk version is less than 4.1.2 before which there wasn't an in-place edit option support available (like -i of sed)

tmpFile="$(mktemp)"
awk '{ $1 = $2 }1' file > "$tmpFile" && mv "$tmpFile" file
rm -f "$tmpFile"
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    `sed 's/^[^\t]*\t\([^\t]*\)$/\1\t\1/'` would do the same thing (provided your `sed` understands `\t` to mean a literal tab). – tripleee Mar 25 '19 at 11:33
  • 1
    @tripleee: I would use `awk` anyday of the week over `sed` ;) – Inian Mar 25 '19 at 11:34
  • 1
    I agree for many purposes, but if your `sed` has `-i` and your Awk doesn't have `-i inplace` that could be a game changer. – tripleee Mar 25 '19 at 11:37