Home > Enterprise >  How to append text at the end of each line (in-place) using sed or awk?
How to append text at the end of each line (in-place) using sed or awk?

Time:02-20

Existing table(sam.txt):

 36419 36418
 36418 36417
 36417 36416
 36416 36415

Desired output:

 36419 36418 1
 36418 36417 2
 36417 36416 3
 36416 36415 3

I want to append 1,2,3,4 as extra column. I have tried below sed command but I cannot loop line number $NUMBER as gives syntax error?

linecount=$(wc -l < sam.txt)
for (( NUMBER=1; NUMBER<=linecount; NUMBER   ))
do  
   sed -i "$NUMBERs/.*/& $b/" sam.txt
done

Update: Removed vertical bars between cells as it was causing confusion. I kept that vertical bars to render as HTML table but it didn't load as intended.

CodePudding user response:

This replies to the original question.

Instead of running sed multiple times, generate a single sed script and run that just once.

#! /bin/bash
lines=$(wc -l < "$1")
{
    echo '1s/$/C/'
    echo '2s/$/----/'
    for ((n=3; n<=lines;   n)) ; do
        echo $n's/$/'$((n-2))/
    done
    echo 's/$/|/'
} | sed -f- "$1"

CodePudding user response:

In awk $0 gives the whole line and you can add text as needed.We declare a variable a that we increment before using it which means that it is one on the first line. We then print the whole line a space the variable a

  • we run:
~/tests $ cat sam.txt | awk '{   a; print $0 " " a  }'   

Which outputs

36419 36418 1
36418 36417 2                                
36417 36416 3
36416 36415 4

CodePudding user response:

$ awk '{print $0, NR}' sam.txt
36419 36418 1
36418 36417 2
36417 36416 3
36416 36415 4

If you want to modify the original file then with GNU awk:

awk -i inplace '{print $0, NR}' sam.txt

or with any awk:

awk '{print $0, NR}' sam.txt > tmp && mv tmp sam.txt

That last script is what gawk, sed, perl, ruby, etc. do behind the scenes anyway, none of them really do "inplace" editing, they all internally use a temp file.

  • Related