'How to append text at the end of each line (in-place) using sed or awk?
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.
Solution 1:[1]
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"
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | choroba |
| Solution 2 |
