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

I am looking for other alternatives / more intelligent 1 liners for the next command, which should add a value to the requested column number. I tried to execute the following sed command to correctly use the value 4 for the 4th column. [Necessity: since I have such a file that contains 1000 records, and many times I need to add a column between them at any position.] My ascript is available only for small scales.

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.

+4
source share
4 answers

One way to use awk . Pass two script arguments, the column number and the value to insert. The script increases the number of fields ( NF ) and goes through the last to the specified position and inserts a new value there.

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 the following output:

 1|2|3|four|5 1|2|3|four|5 1|2|3|four|5 1|2|3|four|5 
+6
source

One way to use coreutils and replace a process:

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

In one case, using coreutils and process replacement:

 sed 's/3|/3|4|/' 1.txt 
+1
source

All Articles