51

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.

5 Answers 5

53

You can do like this:

awk '$35=$35"$"'
0
17

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

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

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
  • 1
    BEGIN {OFS=FS} to do it only once
    – Mat M
    Apr 29, 2021 at 13:10
4

If the field delimiter is <space>:

sed 's/  */$&/35'
3
  • If the field delimiter is unknown: sed 's/./$&/35'
    – Underverse
    Jul 6, 2015 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, 2015 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, 2015 at 1: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
1
  • awk '$1=mktime($1)' FS=, OFS=, oldfile > newfile ... replaced a million timestamps in a few seconds!! :)
    – roblogic
    Nov 10, 2017 at 4:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .