sed / awk - inplace or inline edit

I need to remove the '&' from a file.

In each line of the file, the fields are separated by ^K.
I only want to remove '&' if it exists in field number 9. (example of field 9: abc&xyz)
I need to do an in place/in line edit.

So far I have accomplished the following:

awk -F '^K' '{print $9}' $file | grep "&" | sed 's/&//g' > ./log

In the above line - awk gets the field 9
- filtering using grep and only looking for field 9 with '&'
- sed removes the '&' from the field and sends output to log file (input file is untouched).

But, I want the input file itself to be edited. I dont need a log file.

Any other options or suggestions will be helpful.
Thank you

:slight_smile:

{ rm file && awk '{sub(/&/,"",$9)}1' FS="\\\^K" OFS="^K" > file; } < file

Use gsub for more than one occurrence.

Two Thumbs Up.. - Worked like a charm

Thanks alot.

Would you be kind enough to explain what exactly happens when the command executes? I only understand couple of pieces of it.

:slight_smile:

The content of the input file becomes stdin for rm and awk,
rm ignores it and removes the file, but its file descriptor remains open until both commands (rm and awk) complete, so awk process this "nameless" file and creates a new file.

Thank you.

{ rm file && awk '{sub(/&/,"",$9)}1' FS="\\\^K" OFS="^K" > file; } < file

Questions:

Does the '1' in the awk mean the first occurence of '&'?

For the variable FS why do to have '\\\^K' and different for OFS "^K" ?

Thanks again.

sub removes (replaces with "") the first occurrence of & in the 9th field (use gsub for global substitution or GNU Awk's gensub for more articulated substitutions).
1 is just a shortcut, it means print the current record;
it can be explained like this:

1!=0 -> true -> use default action -> print $0

FS and OFS are treated differently, so in the first case we have to escape the ^ character.

If ^K is the character VT 'vertical tab'\v (ascii 11(10)), modify the command :

{ rm file && awk '{sub(/&/,"",$9)}1' FS="^K" OFS="^K" > file; } < file

You get ^K by entering Ctrl/V+CTRL/K

Jean-Pierre.