I have a text file with one line having few words separated by space and I need to insert another word on "n"th column/field so that previous word should shift right (to n+1st column). how can I do that?
It seems we can do using awk but unable to figure out.
but, of course, you should add some error checking to be sure that all of the operands are present, the 1st is the name of an existing file, and that the last one is a numeric string.
If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .
To further explain what Akshay Hegde said, an awk program consists of pairs of the following form:
pattern { action }
If the given pattern evaluates to a non-zero value for the current input line, the statements included in the action are executed for that line. If pattern is missing, the statements in action will be performed for every input line.
If a pattern is specified and there is no { action } , the action defaults to print (which is shorthand for print $0 ) which prints the current line.
So, the program:
{$f = w OFS $f}1
which is equivalent to:
{$f = w OFS $f}
1
contains two pairs. The first has no pattern and sets the field named by f to the given word followed by the output field separator followed by the original contents of that field. The second pair has no action and since 1 is non-zero, prints the (modified) current line.
The 1 here replace 1 {print $0}
You can also remove the 1 since no pattern gives true and just do: {print $0}
or {print}
and since expression before also does not have any pattern, just the code {code} , we can put the print there too since its always true. {$1=$2 OFS $1;print}
Do study some tutorial for awk and you will see how it works.