49

Given: there are 40 columns in a record. I want to replace the 35th column so that the 35th column will be replaced with the content of the 35th column and a "$" symbol. What came to mind is something like:

awk '{print $1" "$2" "...$35"$ "$36...$40}'

It works but because it is infeasible when the number of column is as large as 10k. I need a better way to do this.

Thomas Dickey
  • 75,040
  • 9
  • 171
  • 268
Marcus Thornton
  • 1,091
  • 3
  • 13
  • 16

5 Answers5

51

You can do like this:

awk '$35=$35"$"'
cuonglm
  • 150,973
  • 38
  • 327
  • 406
17

There are probably more efficient ways to do this. With that caveat:

awk '{$35 = $35"$"; print}' infile > outfile
jasonwryan
  • 71,734
  • 34
  • 193
  • 226
9

To reserve the original Field-Seprator, I did this. The column I wanted to blank-out was number $12.

awk -F"\t" '{OFS=FS}{ $12="" ; print   }' infile.txt > outfile.txt

With gawk -i , if you have it,you can edit the file in place.

z atef
  • 1,057
  • 9
  • 9
4

If the field delimiter is <space>:

sed 's/  */$&/35'
mikeserv
  • 57,448
  • 9
  • 113
  • 229
  • If the field delimiter is unknown: `sed 's/./$&/35'` – Underverse Jul 06 '15 at 01:38
  • @Underverse - I don't think that's the same thing. That should prefix the 35th char on an input line w/ the char `$` - delimited or not. The thing above should affix the 35th occurrence of any number of delimiter chars - in other words, the 35th field - with the char `$` - no matter how chars are in each field. – mikeserv Jul 06 '15 at 01:43
  • Ah, "40 columns in a record". I read 'the 35th column' as literally 'the 35th character column of the text file'. – Underverse Jul 06 '15 at 01:57
1

Had issues using the "approved" answers, it would replace more than just the first column in the file. I use this generic command:

awk '$[column]="[replace]"' FS=, OFS=, inputfile > outputfile

Where:

  • [column] = column you want to change starting with 1 (not 0)
  • [replace] = text you want to replace
perror
  • 3,171
  • 7
  • 33
  • 45
Jason G
  • 11
  • 1
  • `awk '$1=mktime($1)' FS=, OFS=, oldfile > newfile` ... replaced a million timestamps in a few seconds!! :) – roblogic Nov 10 '17 at 04:26