Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column to any position in a file in unix [using awk or sed]

Tags:

shell

unix

sed

awk

I'm looking for other alternatives/more intelligent 1 liner for following command, which should add a value to a requested column number. I tried following following sed command works properly for adding value 4 to the 4th column. [Need: As i have such file which contains 1000 records & many times i need to add a column in between at any position.] My approch is sutaible for smaller scale only.

cat 1.txt

1|2|3|5
1|2|3|5
1|2|3|5
1|2|3|5

sed -i 's/1|2|3|/1|2|3|4|/g' 1.txt

cat 1.txt

1|2|3|4|5
1|2|3|4|5
1|2|3|4|5
1|2|3|4|5

thansk in advance.

like image 800
Mandar Pande Avatar asked Jul 24 '12 08:07

Mandar Pande


2 Answers

Field Separators
http://www.gnu.org/software/gawk/manual/html_node/Field-Separators.html

String Concatenation
http://www.gnu.org/software/gawk/manual/html_node/Concatenation.html

Default pattern and action
http://www.gnu.org/software/gawk/manual/html_node/Very-Simple.html

 awk -v FS='|' -v OFS='|' '{$3=$3"|"4} 1' 1.txt
like image 156
slitvinov Avatar answered Oct 08 '22 20:10

slitvinov


One way using awk. Pass two arguments to the script, the column number and the value to insert. The script increments the number of fields (NF) and goes throught the last one until the indicated position and insert there the new value.

Run this command:

awk -v column=4 -v value="four" '
    BEGIN {
        FS = OFS = "|";
    }
    {
        for ( i = NF + 1; i > column; i-- ) {
            $i = $(i-1);
        }
        $i = value;
        print $0;
    }
' 1.txt

With following output:

1|2|3|four|5
1|2|3|four|5
1|2|3|four|5
1|2|3|four|5
like image 28
Birei Avatar answered Oct 08 '22 20:10

Birei