5

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.

Mandar Pande
  • 12,250
  • 16
  • 45
  • 72

4 Answers4

11

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
slitvinov
  • 5,693
  • 20
  • 31
7

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
Birei
  • 35,723
  • 2
  • 77
  • 82
2

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           )
Thor
  • 45,082
  • 11
  • 119
  • 130
1

One way, using coreutils and process substitution:

sed 's/3|/3|4|/' 1.txt
slhck
  • 36,575
  • 28
  • 148
  • 201
Ragulkumar
  • 11
  • 2
  • 1
    Actually there's no process substitution in this answer. Looks like you copied that header from [another answer](https://stackoverflow.com/a/11628164/56541), possibly without understanding it. (Is `sed` a coreutil anyway?) – David Z Nov 19 '17 at 02:22