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

35,053

Solution 1

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

Solution 2

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

Solution 3

One way using coreutils and process substitution:

f=1.txt
paste -d'|'                       \
  <(cut -d'|' -f1-3 $f          ) \
  <(yes  4 | head -n`wc -l < $f`) \
  <(cut -d'|' -f4- $f           )

Solution 4

One way, using coreutils and process substitution:

sed 's/3|/3|4|/' 1.txt
Share:
35,053
Mandar Pande
Author by

Mandar Pande

Python Enthusiast

Updated on July 09, 2022

Comments

  • Mandar Pande
    Mandar Pande almost 2 years

    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.

  • David Z
    David Z over 6 years
    Actually there's no process substitution in this answer. Looks like you copied that header from another answer, possibly without understanding it. (Is sed a coreutil anyway?)