26

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.

33

You can do like this:

awk '$35=$35"$"'
8

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

awk '{$35 = $35"$"; print}' infile > outfile
3

If the field delimiter is <space>:

sed 's/  */$&/35'
  • If the field delimiter is unknown: sed 's/./$&/35' – Underverse Jul 6 '15 at 1: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 6 '15 at 1:43
  • Ah, "40 columns in a record". I read 'the 35th column' as literally 'the 35th character column of the text file'. – Underverse Jul 6 '15 at 1:57
2

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.

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
  • awk '$1=mktime($1)' FS=, OFS=, oldfile > newfile ... replaced a million timestamps in a few seconds!! :) – roblogic Nov 10 '17 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.